Replace SIZEOF_REGISTER with sizeof(mgreg_t) for consistency with sizeof(gpointer)
[mono.git] / mono / mini / aot-runtime.c
1 /*
2  * aot-runtime.c: mono Ahead of Time compiler
3  *
4  * Author:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Zoltan Varga (vargaz@gmail.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  */
10
11 #include "config.h"
12 #include <sys/types.h>
13 #ifdef HAVE_UNISTD_H
14 #include <unistd.h>
15 #endif
16 #include <fcntl.h>
17 #include <string.h>
18 #ifdef HAVE_SYS_MMAN_H
19 #include <sys/mman.h>
20 #endif
21
22 #if HOST_WIN32
23 #include <winsock2.h>
24 #include <windows.h>
25 #endif
26
27 #ifdef HAVE_EXECINFO_H
28 #include <execinfo.h>
29 #endif
30
31 #include <errno.h>
32 #include <sys/stat.h>
33
34 #ifdef HAVE_SYS_WAIT_H
35 #include <sys/wait.h>  /* for WIFEXITED, WEXITSTATUS */
36 #endif
37
38 #ifdef HAVE_DL_ITERATE_PHDR
39 #include <link.h>
40 #endif
41
42 #include <mono/metadata/tabledefs.h>
43 #include <mono/metadata/class.h>
44 #include <mono/metadata/object.h>
45 #include <mono/metadata/tokentype.h>
46 #include <mono/metadata/appdomain.h>
47 #include <mono/metadata/debug-helpers.h>
48 #include <mono/metadata/assembly.h>
49 #include <mono/metadata/metadata-internals.h>
50 #include <mono/metadata/marshal.h>
51 #include <mono/metadata/gc-internal.h>
52 #include <mono/metadata/monitor.h>
53 #include <mono/metadata/threads-types.h>
54 #include <mono/utils/mono-logger-internal.h>
55 #include <mono/utils/mono-mmap.h>
56 #include "mono/utils/mono-compiler.h"
57 #include <mono/utils/mono-counters.h>
58
59 #include "mini.h"
60 #include "version.h"
61
62 #ifndef DISABLE_AOT
63
64 #ifdef TARGET_WIN32
65 #define SHARED_EXT ".dll"
66 #elif ((defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__)) || defined(__MACH__)) && !defined(__linux__)
67 #define SHARED_EXT ".dylib"
68 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
69 #define SHARED_EXT ".dylib"
70 #else
71 #define SHARED_EXT ".so"
72 #endif
73
74 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
75 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
76
77 typedef struct MonoAotModule {
78         char *aot_name;
79         /* Pointer to the Global Offset Table */
80         gpointer *got;
81         GHashTable *name_cache;
82         GHashTable *extra_methods;
83         /* Maps methods to their code */
84         GHashTable *method_to_code;
85         /* Maps pointers into the method info to the methods themselves */
86         GHashTable *method_ref_to_method;
87         MonoAssemblyName *image_names;
88         char **image_guids;
89         MonoAssembly *assembly;
90         MonoImage **image_table;
91         guint32 image_table_len;
92         gboolean out_of_date;
93         gboolean plt_inited;
94         guint8 *mem_begin;
95         guint8 *mem_end;
96         guint8 *code;
97         guint8 *code_end;
98         guint8 *plt;
99         guint8 *plt_end;
100         guint8 *blob;
101         gint32 *code_offsets;
102         /* This contains <offset, index> pairs sorted by offset */
103         /* This is needed because LLVM emitted methods can be in any order */
104         gint32 *sorted_code_offsets;
105         gint32 sorted_code_offsets_len;
106         guint32 *method_info_offsets;
107         guint32 *got_info_offsets;
108         guint32 *ex_info_offsets;
109         guint32 *class_info_offsets;
110         guint32 *methods_loaded;
111         guint16 *class_name_table;
112         guint32 *extra_method_table;
113         guint32 *extra_method_info_offsets;
114         guint8 *unwind_info;
115
116         /* Points to the mono EH data created by LLVM */
117         guint8 *mono_eh_frame;
118
119         /* Points to the trampolines */
120         guint8 *trampolines [MONO_AOT_TRAMP_NUM];
121         /* The first unused trampoline of each kind */
122         guint32 trampoline_index [MONO_AOT_TRAMP_NUM];
123
124         MonoAotFileInfo info;
125
126         gpointer *globals;
127         MonoDl *sofile;
128 } MonoAotModule;
129
130 static GHashTable *aot_modules;
131 #define mono_aot_lock() EnterCriticalSection (&aot_mutex)
132 #define mono_aot_unlock() LeaveCriticalSection (&aot_mutex)
133 static CRITICAL_SECTION aot_mutex;
134
135 /* 
136  * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
137  * AOT modules registered by mono_aot_register_module ().
138  */
139 static GHashTable *static_aot_modules;
140
141 /*
142  * Maps MonoJitInfo* to the aot module they belong to, this can be different
143  * from ji->method->klass->image's aot module for generic instances.
144  */
145 static GHashTable *ji_to_amodule;
146
147 /*
148  * Whenever to AOT compile loaded assemblies on demand and store them in
149  * a cache under $HOME/.mono/aot-cache.
150  */
151 static gboolean use_aot_cache = FALSE;
152
153 /*
154  * Whenever to spawn a new process to AOT a file or do it in-process. Only relevant if
155  * use_aot_cache is TRUE.
156  */
157 static gboolean spawn_compiler = TRUE;
158
159 /* For debugging */
160 static gint32 mono_last_aot_method = -1;
161
162 static gboolean make_unreadable = FALSE;
163 static guint32 name_table_accesses = 0;
164 static guint32 n_pagefaults = 0;
165
166 /* Used to speed-up find_aot_module () */
167 static gsize aot_code_low_addr = (gssize)-1;
168 static gsize aot_code_high_addr = 0;
169
170 static GHashTable *aot_jit_icall_hash;
171
172 static void
173 init_plt (MonoAotModule *info);
174
175 /*****************************************************/
176 /*                 AOT RUNTIME                       */
177 /*****************************************************/
178
179 /*
180  * load_image:
181  *
182  *   Load one of the images referenced by AMODULE. Returns NULL if the image is not
183  * found, and sets the loader error if SET_ERROR is TRUE.
184  */
185 static MonoImage *
186 load_image (MonoAotModule *amodule, int index, gboolean set_error)
187 {
188         MonoAssembly *assembly;
189         MonoImageOpenStatus status;
190
191         g_assert (index < amodule->image_table_len);
192
193         if (amodule->image_table [index])
194                 return amodule->image_table [index];
195         if (amodule->out_of_date)
196                 return NULL;
197
198         assembly = mono_assembly_load (&amodule->image_names [index], amodule->assembly->basedir, &status);
199         if (!assembly) {
200                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable because dependency %s is not found.\n", amodule->aot_name, amodule->image_names [index].name);
201                 amodule->out_of_date = TRUE;
202
203                 if (set_error) {
204                         char *full_name = mono_stringify_assembly_name (&amodule->image_names [index]);
205                         mono_loader_set_error_assembly_load (full_name, FALSE);
206                         g_free (full_name);
207                 }
208                 return NULL;
209         }
210
211         if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
212                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date (Older than dependency %s).\n", amodule->aot_name, amodule->image_names [index].name);
213                 amodule->out_of_date = TRUE;
214                 return NULL;
215         }
216
217         amodule->image_table [index] = assembly->image;
218         return assembly->image;
219 }
220
221 static inline gint32
222 decode_value (guint8 *ptr, guint8 **rptr)
223 {
224         guint8 b = *ptr;
225         gint32 len;
226         
227         if ((b & 0x80) == 0){
228                 len = b;
229                 ++ptr;
230         } else if ((b & 0x40) == 0){
231                 len = ((b & 0x3f) << 8 | ptr [1]);
232                 ptr += 2;
233         } else if (b != 0xff) {
234                 len = ((b & 0x1f) << 24) |
235                         (ptr [1] << 16) |
236                         (ptr [2] << 8) |
237                         ptr [3];
238                 ptr += 4;
239         }
240         else {
241                 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
242                 ptr += 5;
243         }
244         if (rptr)
245                 *rptr = ptr;
246
247         //printf ("DECODE: %d.\n", len);
248         return len;
249 }
250
251 /*
252  * mono_aot_get_method:
253  *
254  *   Decode an offset table emitted by emit_offset_table (), returning the INDEXth
255  * entry.
256  */
257 static guint32
258 mono_aot_get_offset (guint32 *table, int index)
259 {
260         int i, group, ngroups, index_entry_size;
261         int start_offset, offset, noffsets, group_size;
262         guint8 *data_start, *p;
263         guint32 *index32 = NULL;
264         guint16 *index16 = NULL;
265         
266         noffsets = table [0];
267         group_size = table [1];
268         ngroups = table [2];
269         index_entry_size = table [3];
270         group = index / group_size;
271
272         if (index_entry_size == 2) {
273                 index16 = (guint16*)&table [4];
274                 data_start = (guint8*)&index16 [ngroups];
275                 p = data_start + index16 [group];
276         } else {
277                 index32 = (guint32*)&table [4];
278                 data_start = (guint8*)&index32 [ngroups];
279                 p = data_start + index32 [group];
280         }
281
282         /* offset will contain the value of offsets [group * group_size] */
283         offset = start_offset = decode_value (p, &p);
284         for (i = group * group_size + 1; i <= index; ++i) {
285                 offset += decode_value (p, &p);
286         }
287
288         //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
289
290         return offset;
291 }
292
293 static MonoMethod*
294 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
295
296 static MonoClass*
297 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
298
299 static MonoGenericInst*
300 decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
301 {
302         int type_argc, i;
303         MonoType **type_argv;
304         MonoGenericInst *inst;
305         guint8 *p = buf;
306
307         type_argc = decode_value (p, &p);
308         type_argv = g_new0 (MonoType*, type_argc);
309
310         for (i = 0; i < type_argc; ++i) {
311                 MonoClass *pclass = decode_klass_ref (module, p, &p);
312                 if (!pclass) {
313                         g_free (type_argv);
314                         return NULL;
315                 }
316                 type_argv [i] = &pclass->byval_arg;
317         }
318
319         inst = mono_metadata_get_generic_inst (type_argc, type_argv);
320         g_free (type_argv);
321
322         *endbuf = p;
323
324         return inst;
325 }
326
327 static gboolean
328 decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf)
329 {
330         gboolean has_class_inst, has_method_inst;
331         guint8 *p = buf;
332
333         has_class_inst = decode_value (p, &p);
334         if (has_class_inst) {
335                 ctx->class_inst = decode_generic_inst (module, p, &p);
336                 if (!ctx->class_inst)
337                         return FALSE;
338         }
339         has_method_inst = decode_value (p, &p);
340         if (has_method_inst) {
341                 ctx->method_inst = decode_generic_inst (module, p, &p);
342                 if (!ctx->method_inst)
343                         return FALSE;
344         }
345
346         *endbuf = p;
347         return TRUE;
348 }
349
350 static MonoClass*
351 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
352 {
353         MonoImage *image;
354         MonoClass *klass, *eklass;
355         guint32 token, rank;
356         guint8 *p = buf;
357
358         token = decode_value (p, &p);
359         if (token == 0) {
360                 *endbuf = p;
361                 return NULL;
362         }
363         if (mono_metadata_token_table (token) == 0) {
364                 image = load_image (module, decode_value (p, &p), TRUE);
365                 if (!image)
366                         return NULL;
367                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + token);
368         } else if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
369                 if (token == MONO_TOKEN_TYPE_SPEC) {
370                         MonoTypeEnum type = decode_value (p, &p);
371
372                         if (type == MONO_TYPE_GENERICINST) {
373                                 MonoClass *gclass;
374                                 MonoGenericContext ctx;
375                                 MonoType *type;
376
377                                 gclass = decode_klass_ref (module, p, &p);
378                                 if (!gclass)
379                                         return NULL;
380                                 g_assert (gclass->generic_container);
381
382                                 memset (&ctx, 0, sizeof (ctx));
383                                 ctx.class_inst = decode_generic_inst (module, p, &p);
384                                 if (!ctx.class_inst)
385                                         return NULL;
386                                 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
387                                 klass = mono_class_from_mono_type (type);
388                                 mono_metadata_free_type (type);
389                         } else if ((type == MONO_TYPE_VAR) || (type == MONO_TYPE_MVAR)) {
390                                 MonoType *t;
391                                 MonoGenericContainer *container;
392
393                                 int num = decode_value (p, &p);
394                                 gboolean is_method = decode_value (p, &p);
395
396                                 if (is_method) {
397                                         MonoMethod *method_def;
398                                         g_assert (type == MONO_TYPE_MVAR);
399                                         method_def = decode_resolve_method_ref (module, p, &p);
400                                         if (!method_def)
401                                                 return NULL;
402
403                                         container = mono_method_get_generic_container (method_def);
404                                 } else {
405                                         MonoClass *class_def;
406                                         g_assert (type == MONO_TYPE_VAR);
407                                         class_def = decode_klass_ref (module, p, &p);
408                                         if (!class_def)
409                                                 return NULL;
410
411                                         container = class_def->generic_container;
412                                 }
413
414                                 g_assert (container);
415
416                                 // FIXME: Memory management
417                                 t = g_new0 (MonoType, 1);
418                                 t->type = type;
419                                 t->data.generic_param = mono_generic_container_get_param (container, num);
420
421                                 // FIXME: Maybe use types directly to avoid
422                                 // the overhead of creating MonoClass-es
423                                 klass = mono_class_from_mono_type (t);
424
425                                 g_free (t);
426                         } else {
427                                 g_assert_not_reached ();
428                         }
429                 } else {
430                         image = load_image (module, decode_value (p, &p), TRUE);
431                         if (!image)
432                                 return NULL;
433                         klass = mono_class_get (image, token);
434                 }
435         } else if (token == MONO_TOKEN_TYPE_DEF) {
436                 /* Array */
437                 image = load_image (module, decode_value (p, &p), TRUE);
438                 if (!image)
439                         return NULL;
440                 rank = decode_value (p, &p);
441                 eklass = decode_klass_ref (module, p, &p);
442                 klass = mono_array_class_get (eklass, rank);
443         } else {
444                 g_assert_not_reached ();
445         }
446         g_assert (klass);
447
448         *endbuf = p;
449         return klass;
450 }
451
452 static MonoClassField*
453 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
454 {
455         MonoClass *klass = decode_klass_ref (module, buf, &buf);
456         guint32 token;
457         guint8 *p = buf;
458
459         if (!klass)
460                 return NULL;
461
462         token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
463
464         *endbuf = p;
465
466         return mono_class_get_field (klass, token);
467 }
468
469 /* Stores information returned by decode_method_ref () */
470 typedef struct {
471         MonoImage *image;
472         guint32 token;
473         MonoMethod *method;
474         gboolean no_aot_trampoline;
475 } MethodRef;
476
477 /*
478  * decode_method_ref_with_target:
479  *
480  *   Decode a method reference, storing the image/token into a MethodRef structure.
481  * This avoids loading metadata for the method if the caller does not need it. If the method has
482  * no token, then it is loaded from metadata and ref->method is set to the method instance.
483  * If TARGET is non-NULL, abort decoding if it can be determined that the decoded method couldn't resolve to TARGET, and return FALSE.
484  */
485 static gboolean
486 decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf)
487 {
488         guint32 image_index, value;
489         MonoImage *image = NULL;
490         guint8 *p = buf;
491
492         memset (ref, 0, sizeof (MethodRef));
493
494         value = decode_value (p, &p);
495         image_index = value >> 24;
496
497         if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
498                 ref->no_aot_trampoline = TRUE;
499                 value = decode_value (p, &p);
500                 image_index = value >> 24;
501         }
502
503         if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) {
504                 if (target && target->wrapper_type)
505                         return FALSE;
506         }
507
508         if (image_index == MONO_AOT_METHODREF_WRAPPER) {
509                 guint32 wrapper_type;
510
511                 wrapper_type = decode_value (p, &p);
512
513                 if (target && target->wrapper_type != wrapper_type)
514                         return FALSE;
515
516                 /* Doesn't matter */
517                 image = mono_defaults.corlib;
518
519                 switch (wrapper_type) {
520                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
521                         MonoMethod *m = decode_resolve_method_ref (module, p, &p);
522
523                         if (!m)
524                                 return FALSE;
525                         mono_class_init (m->klass);
526                         ref->method = mono_marshal_get_remoting_invoke_with_check (m);
527                         break;
528                 }
529                 case MONO_WRAPPER_PROXY_ISINST: {
530                         MonoClass *klass = decode_klass_ref (module, p, &p);
531                         if (!klass)
532                                 return FALSE;
533                         ref->method = mono_marshal_get_proxy_cancast (klass);
534                         break;
535                 }
536                 case MONO_WRAPPER_LDFLD:
537                 case MONO_WRAPPER_LDFLDA:
538                 case MONO_WRAPPER_STFLD:
539                 case MONO_WRAPPER_ISINST: {
540                         MonoClass *klass = decode_klass_ref (module, p, &p);
541                         if (!klass)
542                                 return FALSE;
543                         if (wrapper_type == MONO_WRAPPER_LDFLD)
544                                 ref->method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
545                         else if (wrapper_type == MONO_WRAPPER_LDFLDA)
546                                 ref->method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
547                         else if (wrapper_type == MONO_WRAPPER_STFLD)
548                                 ref->method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
549                         else if (wrapper_type == MONO_WRAPPER_ISINST)
550                                 ref->method = mono_marshal_get_isinst (klass);
551                         else
552                                 g_assert_not_reached ();
553                         break;
554                 }
555                 case MONO_WRAPPER_LDFLD_REMOTE:
556                         ref->method = mono_marshal_get_ldfld_remote_wrapper (NULL);
557                         break;
558                 case MONO_WRAPPER_STFLD_REMOTE:
559                         ref->method = mono_marshal_get_stfld_remote_wrapper (NULL);
560                         break;
561                 case MONO_WRAPPER_ALLOC: {
562                         int atype = decode_value (p, &p);
563
564                         ref->method = mono_gc_get_managed_allocator_by_type (atype);
565                         break;
566                 }
567                 case MONO_WRAPPER_WRITE_BARRIER:
568                         ref->method = mono_gc_get_write_barrier ();
569                         break;
570                 case MONO_WRAPPER_STELEMREF:
571                         ref->method = mono_marshal_get_stelemref ();
572                         break;
573                 case MONO_WRAPPER_SYNCHRONIZED: {
574                         MonoMethod *m = decode_resolve_method_ref (module, p, &p);
575
576                         if (!m)
577                                 return FALSE;
578                         ref->method = mono_marshal_get_synchronized_wrapper (m);
579                         break;
580                 }
581                 case MONO_WRAPPER_UNKNOWN: {
582                         MonoMethodDesc *desc;
583                         MonoMethod *orig_method;
584                         int subtype = decode_value (p, &p);
585
586                         if (subtype == MONO_AOT_WRAPPER_MONO_ENTER)
587                                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
588                         else if (subtype == MONO_AOT_WRAPPER_MONO_EXIT)
589                                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
590                         else
591                                 g_assert_not_reached ();
592                         orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
593                         g_assert (orig_method);
594                         mono_method_desc_free (desc);
595                         ref->method = mono_monitor_get_fast_path (orig_method);
596                         break;
597                 }
598                 case MONO_WRAPPER_RUNTIME_INVOKE: {
599                         /* Direct wrapper */
600                         MonoMethod *m = decode_resolve_method_ref (module, p, &p);
601
602                         if (!m)
603                                 return FALSE;
604                         ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
605                         break;
606                 }
607                 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
608                         int subtype = decode_value (p, &p);
609
610                         if (subtype == MONO_AOT_WRAPPER_ELEMENT_ADDR) {
611                                 int rank = decode_value (p, &p);
612                                 int elem_size = decode_value (p, &p);
613
614                                 ref->method = mono_marshal_get_array_address (rank, elem_size);
615                         } else {
616                                 g_assert_not_reached ();
617                         }
618                         break;
619                 }
620                 default:
621                         g_assert_not_reached ();
622                 }
623         } else if (image_index == MONO_AOT_METHODREF_WRAPPER_NAME) {
624                 if (target)
625                         return FALSE;
626                 /* Can't decode these */
627                 g_assert_not_reached ();
628         } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
629                 image_index = decode_value (p, &p);
630                 ref->token = decode_value (p, &p);
631
632                 image = load_image (module, image_index, TRUE);
633                 if (!image)
634                         return FALSE;
635         } else if (image_index == MONO_AOT_METHODREF_GINST) {
636                 MonoClass *klass;
637                 MonoGenericContext ctx;
638
639                 /* 
640                  * These methods do not have a token which resolves them, so we 
641                  * resolve them immediately.
642                  */
643                 klass = decode_klass_ref (module, p, &p);
644                 if (!klass)
645                         return FALSE;
646
647                 if (target && target->klass != klass)
648                         return FALSE;
649
650                 image_index = decode_value (p, &p);
651                 ref->token = decode_value (p, &p);
652
653                 image = load_image (module, image_index, TRUE);
654                 if (!image)
655                         return FALSE;
656
657                 ref->method = mono_get_method_full (image, ref->token, NULL, NULL);
658                 if (!ref->method)
659                         return FALSE;
660
661                 memset (&ctx, 0, sizeof (ctx));
662
663                 if (FALSE && klass->generic_class) {
664                         ctx.class_inst = klass->generic_class->context.class_inst;
665                         ctx.method_inst = NULL;
666  
667                         ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
668                 }                       
669
670                 memset (&ctx, 0, sizeof (ctx));
671
672                 if (!decode_generic_context (module, &ctx, p, &p))
673                         return FALSE;
674
675                 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
676         } else if (image_index == MONO_AOT_METHODREF_ARRAY) {
677                 MonoClass *klass;
678                 int method_type;
679
680                 klass = decode_klass_ref (module, p, &p);
681                 if (!klass)
682                         return FALSE;
683                 method_type = decode_value (p, &p);
684                 switch (method_type) {
685                 case 0:
686                         ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank);
687                         break;
688                 case 1:
689                         ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank * 2);
690                         break;
691                 case 2:
692                         ref->method = mono_class_get_method_from_name (klass, "Get", -1);
693                         break;
694                 case 3:
695                         ref->method = mono_class_get_method_from_name (klass, "Address", -1);
696                         break;
697                 case 4:
698                         ref->method = mono_class_get_method_from_name (klass, "Set", -1);
699                         break;
700                 default:
701                         g_assert_not_reached ();
702                 }
703         } else {
704                 g_assert (image_index < MONO_AOT_METHODREF_MIN);
705                 ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
706
707                 image = load_image (module, image_index, TRUE);
708                 if (!image)
709                         return FALSE;
710         }
711
712         *endbuf = p;
713
714         ref->image = image;
715
716         return TRUE;
717 }
718
719 static gboolean
720 decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf)
721 {
722         return decode_method_ref_with_target (module, ref, NULL, buf, endbuf);
723 }
724
725 /*
726  * decode_resolve_method_ref_with_target:
727  *
728  *   Similar to decode_method_ref, but resolve and return the method itself.
729  */
730 static MonoMethod*
731 decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
732 {
733         MethodRef ref;
734         gboolean res;
735
736         res = decode_method_ref_with_target (module, &ref, target, buf, endbuf);
737         if (!res)
738                 return NULL;
739         if (ref.method)
740                 return ref.method;
741         if (!ref.image)
742                 return NULL;
743         return mono_get_method (ref.image, ref.token, NULL);
744 }
745
746 static MonoMethod*
747 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
748 {
749         return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf);
750 }
751
752 static void
753 create_cache_structure (void)
754 {
755         const char *home;
756         char *tmp;
757         int err;
758
759         home = g_get_home_dir ();
760         if (!home)
761                 return;
762
763         tmp = g_build_filename (home, ".mono", NULL);
764         if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
765                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
766 #ifdef HOST_WIN32
767                 err = mkdir (tmp);
768 #else
769                 err = mkdir (tmp, 0777);
770 #endif
771                 if (err) {
772                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
773                         g_free (tmp);
774                         return;
775                 }
776         }
777         g_free (tmp);
778         tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
779         if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
780                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
781 #ifdef HOST_WIN32
782                 err = mkdir (tmp);
783 #else
784                 err = mkdir (tmp, 0777);
785 #endif
786                 if (err) {
787                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
788                         g_free (tmp);
789                         return;
790                 }
791         }
792         g_free (tmp);
793 }
794
795 /*
796  * load_aot_module_from_cache:
797  *
798  *  Experimental code to AOT compile loaded assemblies on demand. 
799  *
800  * FIXME: 
801  * - Add environment variable MONO_AOT_CACHE_OPTIONS
802  * - Add options for controlling the cache size
803  * - Handle full cache by deleting old assemblies lru style
804  * - Add options for excluding assemblies during development
805  * - Maybe add a threshold after an assembly is AOT compiled
806  * - invoking a new mono process is a security risk
807  * - recompile the AOT module if one of its dependencies changes
808  */
809 static MonoDl*
810 load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
811 {
812         char *fname, *cmd, *tmp2, *aot_options;
813         const char *home;
814         MonoDl *module;
815         gboolean res;
816         gchar *out, *err;
817         gint exit_status;
818
819         *aot_name = NULL;
820
821         if (assembly->image->dynamic)
822                 return NULL;
823
824         create_cache_structure ();
825
826         home = g_get_home_dir ();
827
828         tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
829         fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
830         *aot_name = fname;
831         g_free (tmp2);
832
833         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
834         module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
835
836         if (!module) {
837                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");
838
839                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);
840
841                 aot_options = g_strdup_printf ("outfile=%s", fname);
842
843                 if (spawn_compiler) {
844                         /* FIXME: security */
845                         /* FIXME: Has to pass the assembly loading path to the child process */
846                         cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name);
847
848                         res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
849
850 #if !defined(HOST_WIN32) && !defined(__ppc__) && !defined(__ppc64__) && !defined(__powerpc__)
851                         if (res) {
852                                 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
853                                         mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err);
854                                 else
855                                         mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
856                                 g_free (out);
857                                 g_free (err);
858                         }
859 #endif
860                         g_free (cmd);
861                 } else {
862                         res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
863                         if (!res) {
864                                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
865                         } else {
866                                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
867                         }
868                 }
869
870                 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
871
872                 g_free (aot_options);
873         }
874
875         return module;
876 }
877
878 static void
879 find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
880 {
881         if (globals) {
882                 int global_index;
883                 guint16 *table, *entry;
884                 guint16 table_size;
885                 guint32 hash;           
886
887                 /* The first entry points to the hash */
888                 table = globals [0];
889                 globals ++;
890
891                 table_size = table [0];
892                 table ++;
893
894                 hash = mono_metadata_str_hash (name) % table_size;
895
896                 entry = &table [hash * 2];
897
898                 /* Search the hash for the index into the globals table */
899                 global_index = -1;
900                 while (entry [0] != 0) {
901                         guint32 index = entry [0] - 1;
902                         guint32 next = entry [1];
903
904                         //printf ("X: %s %s\n", (char*)globals [index * 2], name);
905
906                         if (!strcmp (globals [index * 2], name)) {
907                                 global_index = index;
908                                 break;
909                         }
910
911                         if (next != 0) {
912                                 entry = &table [next * 2];
913                         } else {
914                                 break;
915                         }
916                 }
917
918                 if (global_index != -1)
919                         *value = globals [global_index * 2 + 1];
920                 else
921                         *value = NULL;
922         } else {
923                 char *err = mono_dl_symbol (module, name, value);
924
925                 if (err)
926                         g_free (err);
927         }
928 }
929
930 static void
931 load_aot_module (MonoAssembly *assembly, gpointer user_data)
932 {
933         char *aot_name;
934         MonoAotModule *amodule;
935         MonoDl *sofile;
936         gboolean usable = TRUE;
937         char *saved_guid = NULL;
938         char *aot_version = NULL;
939         char *runtime_version, *build_info;
940         char *opt_flags = NULL;
941         gpointer *globals;
942         gboolean full_aot = FALSE;
943         MonoAotFileInfo *file_info = NULL;
944         int i;
945         gpointer *got_addr;
946         guint8 *blob;
947         gboolean do_load_image = TRUE;
948
949         if (mono_compile_aot)
950                 return;
951
952         if (assembly->image->aot_module)
953                 /* 
954                  * Already loaded. This can happen because the assembly loading code might invoke
955                  * the assembly load hooks multiple times for the same assembly.
956                  */
957                 return;
958
959         if (assembly->image->dynamic)
960                 return;
961
962         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
963                 return;
964
965         mono_aot_lock ();
966         if (static_aot_modules)
967                 globals = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
968         else
969                 globals = NULL;
970         mono_aot_unlock ();
971
972         if (globals) {
973                 /* Statically linked AOT module */
974                 sofile = NULL;
975                 aot_name = g_strdup_printf ("%s", assembly->aname.name);
976                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
977         } else {
978                 if (use_aot_cache)
979                         sofile = load_aot_module_from_cache (assembly, &aot_name);
980                 else {
981                         char *err;
982                         aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
983
984                         sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
985
986                         if (!sofile) {
987                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err);
988                                 g_free (err);
989                         }
990                 }
991         }
992
993         if (!sofile && !globals) {
994                 if (mono_aot_only) {
995                         fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
996                         exit (1);
997                 }
998                 g_free (aot_name);
999                 return;
1000         }
1001
1002         find_symbol (sofile, globals, "mono_assembly_guid", (gpointer *) &saved_guid);
1003         find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &aot_version);
1004         find_symbol (sofile, globals, "mono_aot_opt_flags", (gpointer *)&opt_flags);
1005         find_symbol (sofile, globals, "mono_runtime_version", (gpointer *)&runtime_version);
1006         find_symbol (sofile, globals, "mono_aot_got_addr", (gpointer *)&got_addr);
1007
1008         if (!aot_version || strcmp (aot_version, MONO_AOT_FILE_VERSION)) {
1009                 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);
1010                 usable = FALSE;
1011         }
1012         else {
1013                 if (!saved_guid || strcmp (assembly->image->guid, saved_guid)) {
1014                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date.\n", aot_name);
1015                         usable = FALSE;
1016                 }
1017         }
1018
1019         build_info = mono_get_runtime_build_info ();
1020         if (!runtime_version || ((strlen (runtime_version) > 0 && strcmp (runtime_version, build_info)))) {
1021                 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);
1022                 usable = FALSE;
1023         }
1024         g_free (build_info);
1025
1026         find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&file_info);
1027         g_assert (file_info);
1028
1029         full_aot = ((MonoAotFileInfo*)file_info)->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1030
1031         if (mono_aot_only && !full_aot) {
1032                 fprintf (stderr, "Can't use AOT image '%s' in aot-only mode because it is not compiled with --aot=full.\n", aot_name);
1033                 exit (1);
1034         }
1035         if (!mono_aot_only && full_aot) {
1036                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled with --aot=full.\n", aot_name);
1037                 usable = FALSE;
1038         }
1039
1040         /* This is no longer needed, LLVM and non-LLVM runtimes should be compatible.
1041         if ((((MonoAotFileInfo*)file_info)->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) {
1042                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled with LLVM.\n", aot_name);
1043                 usable = FALSE;
1044         }
1045         */
1046
1047         if (mini_get_debug_options ()->mdb_optimizations && !(file_info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot) {
1048                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is not compiled for debugging.\n", aot_name);
1049                 usable = FALSE;
1050         }
1051
1052         find_symbol (sofile, globals, "blob", (gpointer*)&blob);
1053
1054         if (usable && ((MonoAotFileInfo*)file_info)->gc_name_index != -1) {
1055                 char *gc_name = (char*)&blob [((MonoAotFileInfo*)file_info)->gc_name_index];
1056                 const char *current_gc_name = mono_gc_get_gc_name ();
1057
1058                 if (strcmp (current_gc_name, gc_name) != 0) {
1059                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled against GC %s, while the current runtime uses GC %s.\n", aot_name, gc_name, current_gc_name);
1060                         usable = FALSE;
1061                 }
1062         }
1063
1064         if (!usable) {
1065                 if (mono_aot_only) {
1066                         fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode.\n", aot_name);
1067                         exit (1);
1068                 } else {
1069                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable.\n", aot_name);
1070                 }
1071                 g_free (aot_name);
1072                 if (sofile)
1073                         mono_dl_close (sofile);
1074                 assembly->image->aot_module = NULL;
1075                 return;
1076         }
1077
1078         amodule = g_new0 (MonoAotModule, 1);
1079         amodule->aot_name = aot_name;
1080         amodule->assembly = assembly;
1081
1082         memcpy (&amodule->info, file_info, sizeof (*file_info));
1083
1084         amodule->got = *got_addr;
1085         amodule->got [0] = assembly->image;
1086         amodule->globals = globals;
1087         amodule->sofile = sofile;
1088         amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
1089         amodule->blob = blob;
1090
1091         /* Read image table */
1092         {
1093                 guint32 table_len, i;
1094                 char *table = NULL;
1095
1096                 find_symbol (sofile, globals, "mono_image_table", (gpointer *)&table);
1097                 g_assert (table);
1098
1099                 table_len = *(guint32*)table;
1100                 table += sizeof (guint32);
1101                 amodule->image_table = g_new0 (MonoImage*, table_len);
1102                 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
1103                 amodule->image_guids = g_new0 (char*, table_len);
1104                 amodule->image_table_len = table_len;
1105                 for (i = 0; i < table_len; ++i) {
1106                         MonoAssemblyName *aname = &(amodule->image_names [i]);
1107
1108                         aname->name = g_strdup (table);
1109                         table += strlen (table) + 1;
1110                         amodule->image_guids [i] = g_strdup (table);
1111                         table += strlen (table) + 1;
1112                         if (table [0] != 0)
1113                                 aname->culture = g_strdup (table);
1114                         table += strlen (table) + 1;
1115                         memcpy (aname->public_key_token, table, strlen (table) + 1);
1116                         table += strlen (table) + 1;                    
1117
1118                         table = ALIGN_PTR_TO (table, 8);
1119                         aname->flags = *(guint32*)table;
1120                         table += 4;
1121                         aname->major = *(guint32*)table;
1122                         table += 4;
1123                         aname->minor = *(guint32*)table;
1124                         table += 4;
1125                         aname->build = *(guint32*)table;
1126                         table += 4;
1127                         aname->revision = *(guint32*)table;
1128                         table += 4;
1129                 }
1130         }
1131
1132         /* Read method and method_info tables */
1133         find_symbol (sofile, globals, "code_offsets", (gpointer*)&amodule->code_offsets);
1134         find_symbol (sofile, globals, "methods", (gpointer*)&amodule->code);
1135         find_symbol (sofile, globals, "methods_end", (gpointer*)&amodule->code_end);
1136         find_symbol (sofile, globals, "method_info_offsets", (gpointer*)&amodule->method_info_offsets);
1137         find_symbol (sofile, globals, "ex_info_offsets", (gpointer*)&amodule->ex_info_offsets);
1138         find_symbol (sofile, globals, "class_info_offsets", (gpointer*)&amodule->class_info_offsets);
1139         find_symbol (sofile, globals, "class_name_table", (gpointer *)&amodule->class_name_table);
1140         find_symbol (sofile, globals, "extra_method_table", (gpointer *)&amodule->extra_method_table);
1141         find_symbol (sofile, globals, "extra_method_info_offsets", (gpointer *)&amodule->extra_method_info_offsets);
1142         find_symbol (sofile, globals, "got_info_offsets", (gpointer*)&amodule->got_info_offsets);
1143         find_symbol (sofile, globals, "specific_trampolines", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC]));
1144         find_symbol (sofile, globals, "static_rgctx_trampolines", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX]));
1145         find_symbol (sofile, globals, "imt_thunks", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK]));
1146         find_symbol (sofile, globals, "unwind_info", (gpointer)&amodule->unwind_info);
1147         find_symbol (sofile, globals, "mem_end", (gpointer*)&amodule->mem_end);
1148
1149         amodule->mem_begin = amodule->code;
1150
1151         find_symbol (sofile, globals, "plt", (gpointer*)&amodule->plt);
1152         find_symbol (sofile, globals, "plt_end", (gpointer*)&amodule->plt_end);
1153
1154         if (file_info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) {
1155                 gpointer *p = NULL;
1156                 find_symbol (sofile, globals, "mono_eh_frame_addr", (gpointer*)&p);
1157                 g_assert (p);
1158                 amodule->mono_eh_frame = *p;
1159         }
1160
1161         if (make_unreadable) {
1162 #ifndef TARGET_WIN32
1163                 guint8 *addr;
1164                 guint8 *page_start, *page_end;
1165                 int err, len;
1166
1167                 addr = amodule->mem_begin;
1168                 len = amodule->mem_end - amodule->mem_begin;
1169
1170                 /* Round down in both directions to avoid modifying data which is not ours */
1171                 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
1172                 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
1173                 if (page_end > page_start) {
1174                         err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
1175                         g_assert (err == 0);
1176                 }
1177 #endif
1178         }
1179
1180         mono_aot_lock ();
1181
1182         aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
1183         aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);
1184
1185         g_hash_table_insert (aot_modules, assembly, amodule);
1186         mono_aot_unlock ();
1187
1188         mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);
1189
1190         assembly->image->aot_module = amodule;
1191
1192         if (mono_aot_only) {
1193                 if (mono_defaults.corlib) {
1194                         /* The second got slot contains the mscorlib got addr */
1195                         MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1196
1197                         amodule->got [1] = mscorlib_amodule->got;
1198                 } else {
1199                         amodule->got [1] = amodule->got;
1200                 }
1201         }
1202
1203         if (mono_gc_is_moving ()) {
1204                 MonoJumpInfo ji;
1205
1206                 memset (&ji, 0, sizeof (ji));
1207                 ji.type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
1208
1209                 amodule->got [2] = mono_resolve_patch_target (NULL, mono_get_root_domain (), NULL, &ji, FALSE);
1210         }
1211
1212         /*
1213          * Since we store methoddef and classdef tokens when referring to methods/classes in
1214          * referenced assemblies, we depend on the exact versions of the referenced assemblies.
1215          * MS calls this 'hard binding'. This means we have to load all referenced assemblies
1216          * non-lazily, since we can't handle out-of-date errors later.
1217          * The cached class info also depends on the exact assemblies.
1218          */
1219 #if defined(__native_client__)
1220         /* TODO: Don't 'load_image' on mscorlib due to a */
1221         /* recursive loading problem.  This should be    */
1222         /* removed if mscorlib is loaded from disk.      */
1223         if (strncmp(assembly->aname.name, "mscorlib", 8)) {
1224                 do_load_image = TRUE;
1225         } else {
1226                 do_load_image = FALSE;
1227         }
1228 #endif
1229         if (do_load_image) {
1230                 for (i = 0; i < amodule->image_table_len; ++i)
1231                         load_image (amodule, i, FALSE);
1232         }
1233
1234         if (amodule->out_of_date) {
1235                 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);
1236                 if (mono_aot_only) {
1237                         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);
1238                         exit (1);
1239                 }
1240         }
1241         else
1242                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
1243 }
1244
1245 /*
1246  * mono_aot_register_globals:
1247  *
1248  *   This is called by the ctor function in AOT images compiled with the
1249  * 'no-dlsym' option.
1250  */
1251 void
1252 mono_aot_register_globals (gpointer *globals)
1253 {
1254         g_assert_not_reached ();
1255 }
1256
1257 /*
1258  * mono_aot_register_module:
1259  *
1260  *   This should be called by embedding code to register AOT modules statically linked
1261  * into the executable. AOT_INFO should be the value of the 
1262  * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
1263  */
1264 void
1265 mono_aot_register_module (gpointer *aot_info)
1266 {
1267         gpointer *globals;
1268         char *aname;
1269
1270         globals = aot_info;
1271         g_assert (globals);
1272
1273         /* Determine the assembly name */
1274         find_symbol (NULL, globals, "mono_aot_assembly_name", (gpointer*)&aname);
1275         g_assert (aname);
1276
1277         /* This could be called before startup */
1278         if (aot_modules)
1279                 mono_aot_lock ();
1280
1281         if (!static_aot_modules)
1282                 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
1283
1284         g_hash_table_insert (static_aot_modules, aname, globals);
1285
1286         if (aot_modules)
1287                 mono_aot_unlock ();
1288 }
1289
1290 void
1291 mono_aot_init (void)
1292 {
1293         InitializeCriticalSection (&aot_mutex);
1294         aot_modules = g_hash_table_new (NULL, NULL);
1295
1296         mono_install_assembly_load_hook (load_aot_module, NULL);
1297
1298         if (g_getenv ("MONO_LASTAOT"))
1299                 mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
1300         if (g_getenv ("MONO_AOT_CACHE"))
1301                 use_aot_cache = TRUE;
1302 }
1303
1304 void
1305 mono_aot_cleanup (void)
1306 {
1307         if (aot_jit_icall_hash)
1308                 g_hash_table_destroy (aot_jit_icall_hash);
1309         if (aot_modules)
1310                 g_hash_table_destroy (aot_modules);
1311 }
1312
1313 static gboolean
1314 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
1315 {
1316         guint32 flags;
1317         MethodRef ref;
1318         gboolean res;
1319
1320         info->vtable_size = decode_value (buf, &buf);
1321         if (info->vtable_size == -1)
1322                 /* Generic type */
1323                 return FALSE;
1324         flags = decode_value (buf, &buf);
1325         info->ghcimpl = (flags >> 0) & 0x1;
1326         info->has_finalize = (flags >> 1) & 0x1;
1327         info->has_cctor = (flags >> 2) & 0x1;
1328         info->has_nested_classes = (flags >> 3) & 0x1;
1329         info->blittable = (flags >> 4) & 0x1;
1330         info->has_references = (flags >> 5) & 0x1;
1331         info->has_static_refs = (flags >> 6) & 0x1;
1332         info->no_special_static_fields = (flags >> 7) & 0x1;
1333         info->is_generic_container = (flags >> 8) & 0x1;
1334
1335         if (info->has_cctor) {
1336                 res = decode_method_ref (module, &ref, buf, &buf);
1337                 if (!res)
1338                         return FALSE;
1339                 info->cctor_token = ref.token;
1340         }
1341         if (info->has_finalize) {
1342                 res = decode_method_ref (module, &ref, buf, &buf);
1343                 if (!res)
1344                         return FALSE;
1345                 info->finalize_image = ref.image;
1346                 info->finalize_token = ref.token;
1347         }
1348
1349         info->instance_size = decode_value (buf, &buf);
1350         info->class_size = decode_value (buf, &buf);
1351         info->packing_size = decode_value (buf, &buf);
1352         info->min_align = decode_value (buf, &buf);
1353
1354         *endbuf = buf;
1355
1356         return TRUE;
1357 }       
1358
1359 gpointer
1360 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
1361 {
1362         int i;
1363         MonoClass *klass = vtable->klass;
1364         MonoAotModule *amodule = klass->image->aot_module;
1365         guint8 *info, *p;
1366         MonoCachedClassInfo class_info;
1367         gboolean err;
1368         MethodRef ref;
1369         gboolean res;
1370
1371         if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !amodule)
1372                 return NULL;
1373
1374         info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1375         p = info;
1376
1377         err = decode_cached_class_info (amodule, &class_info, p, &p);
1378         if (!err)
1379                 return NULL;
1380
1381         for (i = 0; i < slot; ++i)
1382                 decode_method_ref (amodule, &ref, p, &p);
1383
1384         res = decode_method_ref (amodule, &ref, p, &p);
1385         if (!res)
1386                 return NULL;
1387         if (ref.no_aot_trampoline)
1388                 return NULL;
1389
1390         if (mono_metadata_token_index (ref.token) == 0)
1391                 return NULL;
1392
1393         return mono_aot_get_method_from_token (domain, ref.image, ref.token);
1394 }
1395
1396 gboolean
1397 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
1398 {
1399         MonoAotModule *amodule = klass->image->aot_module;
1400         guint8 *p;
1401         gboolean err;
1402
1403         if (klass->rank || !amodule)
1404                 return FALSE;
1405
1406         p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1407
1408         err = decode_cached_class_info (amodule, res, p, &p);
1409         if (!err)
1410                 return FALSE;
1411
1412         return TRUE;
1413 }
1414
1415 /**
1416  * mono_aot_get_class_from_name:
1417  *
1418  *  Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
1419  * using a cache stored in the AOT file.
1420  * Stores the resulting class in *KLASS if found, stores NULL otherwise.
1421  *
1422  * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was 
1423  * found.
1424  */
1425 gboolean
1426 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
1427 {
1428         MonoAotModule *amodule = image->aot_module;
1429         guint16 *table, *entry;
1430         guint16 table_size;
1431         guint32 hash;
1432         char full_name_buf [1024];
1433         char *full_name;
1434         const char *name2, *name_space2;
1435         MonoTableInfo  *t;
1436         guint32 cols [MONO_TYPEDEF_SIZE];
1437         GHashTable *nspace_table;
1438
1439         if (!amodule || !amodule->class_name_table)
1440                 return FALSE;
1441
1442         mono_aot_lock ();
1443
1444         *klass = NULL;
1445
1446         /* First look in the cache */
1447         if (!amodule->name_cache)
1448                 amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
1449         nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
1450         if (nspace_table) {
1451                 *klass = g_hash_table_lookup (nspace_table, name);
1452                 if (*klass) {
1453                         mono_aot_unlock ();
1454                         return TRUE;
1455                 }
1456         }
1457
1458         table_size = amodule->class_name_table [0];
1459         table = amodule->class_name_table + 1;
1460
1461         if (name_space [0] == '\0')
1462                 full_name = g_strdup_printf ("%s", name);
1463         else {
1464                 if (strlen (name_space) + strlen (name) < 1000) {
1465                         sprintf (full_name_buf, "%s.%s", name_space, name);
1466                         full_name = full_name_buf;
1467                 } else {
1468                         full_name = g_strdup_printf ("%s.%s", name_space, name);
1469                 }
1470         }
1471         hash = mono_metadata_str_hash (full_name) % table_size;
1472         if (full_name != full_name_buf)
1473                 g_free (full_name);
1474
1475         entry = &table [hash * 2];
1476
1477         if (entry [0] != 0) {
1478                 t = &image->tables [MONO_TABLE_TYPEDEF];
1479
1480                 while (TRUE) {
1481                         guint32 index = entry [0];
1482                         guint32 next = entry [1];
1483                         guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
1484
1485                         name_table_accesses ++;
1486
1487                         mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
1488
1489                         name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1490                         name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1491
1492                         if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
1493                                 mono_aot_unlock ();
1494                                 *klass = mono_class_get (image, token);
1495
1496                                 /* Add to cache */
1497                                 if (*klass) {
1498                                         mono_aot_lock ();
1499                                         nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
1500                                         if (!nspace_table) {
1501                                                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
1502                                                 g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
1503                                         }
1504                                         g_hash_table_insert (nspace_table, (char*)name2, *klass);
1505                                         mono_aot_unlock ();
1506                                 }
1507                                 return TRUE;
1508                         }
1509
1510                         if (next != 0) {
1511                                 entry = &table [next * 2];
1512                         } else {
1513                                 break;
1514                         }
1515                 }
1516         }
1517
1518         mono_aot_unlock ();
1519         
1520         return TRUE;
1521 }
1522
1523 /*
1524  * decode_mono_eh_frame:
1525  *
1526  *   Decode the EH information emitted by our modified LLVM compiler and construct a
1527  * MonoJitInfo structure from it.
1528  * LOCKING: Acquires the domain lock.
1529  */
1530 static MonoJitInfo*
1531 decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoDomain *domain, 
1532                                                    MonoMethod *method, guint8 *code, 
1533                                                    MonoJitExceptionInfo *clauses, int num_clauses,
1534                                                    int extra_size, GSList **nesting,
1535                                                    int *this_reg, int *this_offset)
1536 {
1537         guint8 *p;
1538         guint8 *fde, *cie, *code_start, *code_end;
1539         int version, fde_count;
1540         gint32 *table;
1541         int i, j, pos, left, right, offset, offset1, offset2, code_len;
1542         MonoJitExceptionInfo *ei;
1543         guint32 fde_len, ei_len, nested_len, nindex;
1544         gpointer *type_info;
1545         MonoJitInfo *jinfo;
1546         MonoLLVMFDEInfo info;
1547
1548         g_assert (amodule->mono_eh_frame);
1549
1550         p = amodule->mono_eh_frame;
1551
1552         /* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
1553
1554         /* Header */
1555         version = *p;
1556         g_assert (version == 1);
1557         p ++;
1558         p = ALIGN_PTR_TO (p, 4);
1559
1560         fde_count = *(guint32*)p;
1561         p += 4;
1562         table = (gint32*)p;
1563
1564         /* There is +1 entry in the table */
1565         cie = p + ((fde_count + 1) * 8);
1566
1567         /* Binary search in the table to find the entry for code */
1568         offset = code - amodule->mono_eh_frame;
1569
1570         left = 0;
1571         right = fde_count;
1572         while (TRUE) {
1573                 pos = (left + right) / 2;
1574
1575                 offset1 = table [(pos * 2)];
1576                 if (pos + 1 == fde_count)
1577                         /* FIXME: */
1578                         offset2 = amodule->code_end - amodule->code;
1579                 else
1580                         offset2 = table [(pos + 1) * 2];
1581
1582                 if (offset < offset1)
1583                         right = pos;
1584                 else if (offset >= offset2)
1585                         left = pos + 1;
1586                 else
1587                         break;
1588         }
1589
1590         code_start = amodule->mono_eh_frame + table [(pos * 2)];
1591         /* This won't overflow because there is +1 entry in the table */
1592         code_end = amodule->mono_eh_frame + table [(pos * 2) + 2];
1593         code_len = code_end - code_start;
1594
1595         g_assert (code >= code_start && code < code_end);
1596
1597         fde = amodule->mono_eh_frame + table [(pos * 2) + 1];   
1598         /* This won't overflow because there is +1 entry in the table */
1599         fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
1600
1601         mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info);
1602         ei = info.ex_info;
1603         ei_len = info.ex_info_len;
1604         type_info = info.type_info;
1605         *this_reg = info.this_reg;
1606         *this_offset = info.this_offset;
1607
1608         /* Count number of nested clauses */
1609         nested_len = 0;
1610         for (i = 0; i < ei_len; ++i) {
1611                 gint32 cindex1 = *(gint32*)type_info [i];
1612                 GSList *l;
1613
1614                 for (l = nesting [cindex1]; l; l = l->next) {
1615                         gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
1616
1617                         for (j = 0; j < ei_len; ++j) {
1618                                 gint32 cindex2 = *(gint32*)type_info [j];
1619
1620                                 if (cindex2 == nesting_cindex)
1621                                         nested_len ++;
1622                         }
1623                 }
1624         }
1625
1626         /*
1627          * LLVM might represent one IL region with multiple regions, so have to
1628          * allocate a new JI.
1629          */
1630         jinfo = 
1631                 mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * (ei_len + nested_len)) + extra_size);
1632
1633         jinfo->code_size = code_len;
1634         jinfo->used_regs = mono_cache_unwind_info (info.unw_info, info.unw_info_len);
1635         jinfo->method = method;
1636         jinfo->code_start = code;
1637         jinfo->domain_neutral = 0;
1638         /* This signals that used_regs points to a normal cached unwind info */
1639         jinfo->from_aot = 0;
1640         jinfo->num_clauses = ei_len + nested_len;
1641
1642         for (i = 0; i < ei_len; ++i) {
1643                 /*
1644                  * orig_jinfo contains the original IL exception info saved by the AOT
1645                  * compiler, we have to combine that with the information produced by LLVM
1646                  */
1647                 /* The type_info entries contain IL clause indexes */
1648                 int clause_index = *(gint32*)type_info [i];
1649                 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
1650                 MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
1651
1652                 g_assert (clause_index < num_clauses);
1653                 jei->flags = orig_jei->flags;
1654                 jei->data.catch_class = orig_jei->data.catch_class;
1655
1656                 jei->try_start = ei [i].try_start;
1657                 jei->try_end = ei [i].try_end;
1658                 jei->handler_start = ei [i].handler_start;
1659         }
1660
1661         /* See exception_cb () in mini-llvm.c as to why this is needed */
1662         nindex = ei_len;
1663         for (i = 0; i < ei_len; ++i) {
1664                 gint32 cindex1 = *(gint32*)type_info [i];
1665                 GSList *l;
1666
1667                 for (l = nesting [cindex1]; l; l = l->next) {
1668                         gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
1669
1670                         for (j = 0; j < ei_len; ++j) {
1671                                 gint32 cindex2 = *(gint32*)type_info [j];
1672
1673                                 if (cindex2 == nesting_cindex) {
1674                                         /* 
1675                                          * The try interval comes from the nested clause, everything else from the
1676                                          * nesting clause.
1677                                          */
1678                                         memcpy (&jinfo->clauses [nindex], &jinfo->clauses [j], sizeof (MonoJitExceptionInfo));
1679                                         jinfo->clauses [nindex].try_start = jinfo->clauses [i].try_start;
1680                                         jinfo->clauses [nindex].try_end = jinfo->clauses [i].try_end;
1681                                         nindex ++;
1682                                 }
1683                         }
1684                 }
1685         }
1686         g_assert (nindex == ei_len + nested_len);
1687
1688         return jinfo;
1689 }
1690
1691 /*
1692  * LOCKING: Acquires the domain lock.
1693  */
1694 static MonoJitInfo*
1695 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain, 
1696                                                          MonoMethod *method, guint8* ex_info, guint8 *addr,
1697                                                          guint8 *code, guint32 code_len)
1698 {
1699         int i, buf_len, num_clauses;
1700         MonoJitInfo *jinfo;
1701         guint used_int_regs, flags;
1702         gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes;
1703         gboolean from_llvm;
1704         guint8 *p;
1705         int generic_info_size, try_holes_info_size, num_holes, this_reg, this_offset;
1706
1707         /* Load the method info from the AOT file */
1708
1709         p = ex_info;
1710         flags = decode_value (p, &p);
1711         has_generic_jit_info = (flags & 1) != 0;
1712         has_dwarf_unwind_info = (flags & 2) != 0;
1713         has_clauses = (flags & 4) != 0;
1714         has_seq_points = (flags & 8) != 0;
1715         from_llvm = (flags & 16) != 0;
1716         has_try_block_holes = (flags & 32) != 0;
1717
1718         if (has_dwarf_unwind_info) {
1719                 guint32 offset;
1720
1721                 offset = decode_value (p, &p);
1722                 g_assert (offset < (1 << 30));
1723                 used_int_regs = offset;
1724         } else {
1725                 used_int_regs = decode_value (p, &p);
1726         }
1727         if (has_generic_jit_info)
1728                 generic_info_size = sizeof (MonoGenericJitInfo);
1729         else
1730                 generic_info_size = 0;
1731
1732         if (has_try_block_holes) {
1733                 num_holes = decode_value (p, &p);
1734                 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
1735         } else {
1736                 num_holes = try_holes_info_size = 0;
1737         }
1738         /* Exception table */
1739         if (has_clauses)
1740                 num_clauses = decode_value (p, &p);
1741         else
1742                 num_clauses = 0;
1743
1744         if (from_llvm) {
1745                 MonoJitExceptionInfo *clauses;
1746                 GSList **nesting;
1747
1748                 /*
1749                  * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
1750                  * section.
1751                  */
1752                 clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
1753                 nesting = g_new0 (GSList*, num_clauses);
1754
1755                 for (i = 0; i < num_clauses; ++i) {
1756                         MonoJitExceptionInfo *ei = &clauses [i];
1757
1758                         ei->flags = decode_value (p, &p);
1759
1760                         if (decode_value (p, &p))
1761                                 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
1762
1763                         /* Read the list of nesting clauses */
1764                         while (TRUE) {
1765                                 int nesting_index = decode_value (p, &p);
1766                                 if (nesting_index == -1)
1767                                         break;
1768                                 nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
1769                         }
1770                 }
1771
1772                 jinfo = decode_llvm_mono_eh_frame (amodule, domain, method, code, clauses, num_clauses, generic_info_size + try_holes_info_size, nesting, &this_reg, &this_offset);
1773                 jinfo->from_llvm = 1;
1774
1775                 g_free (clauses);
1776                 for (i = 0; i < num_clauses; ++i)
1777                         g_slist_free (nesting [i]);
1778                 g_free (nesting);
1779         } else {
1780                 jinfo = 
1781                         mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size);
1782                 jinfo->num_clauses = num_clauses;
1783
1784                 for (i = 0; i < jinfo->num_clauses; ++i) {
1785                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
1786
1787                         ei->flags = decode_value (p, &p);
1788
1789                         ei->exvar_offset = decode_value (p, &p);
1790
1791                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
1792                                 ei->data.filter = code + decode_value (p, &p);
1793                         else {
1794                                 if (decode_value (p, &p))
1795                                         ei->data.catch_class = decode_klass_ref (amodule, p, &p);
1796                         }
1797
1798                         ei->try_start = code + decode_value (p, &p);
1799                         ei->try_end = code + decode_value (p, &p);
1800                         ei->handler_start = code + decode_value (p, &p);
1801                 }
1802
1803                 jinfo->code_size = code_len;
1804                 jinfo->used_regs = used_int_regs;
1805                 jinfo->method = method;
1806                 jinfo->code_start = code;
1807                 jinfo->domain_neutral = 0;
1808                 jinfo->from_aot = 1;
1809         }
1810
1811         if (has_generic_jit_info) {
1812                 MonoGenericJitInfo *gi;
1813
1814                 jinfo->has_generic_jit_info = 1;
1815
1816                 gi = mono_jit_info_get_generic_jit_info (jinfo);
1817                 g_assert (gi);
1818
1819                 if (from_llvm) {
1820                         gi->has_this = this_reg != -1;
1821                         gi->this_reg = this_reg;
1822                         gi->this_offset = this_offset;
1823                 } else {
1824                         gi->has_this = decode_value (p, &p);
1825                         gi->this_reg = decode_value (p, &p);
1826                         gi->this_offset = decode_value (p, &p);
1827                 }
1828
1829                 /* This currently contains no data */
1830                 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
1831
1832                 jinfo->method = decode_resolve_method_ref (amodule, p, &p);
1833         }
1834
1835         if (has_try_block_holes) {
1836                 MonoTryBlockHoleTableJitInfo *table;
1837
1838                 jinfo->has_try_block_holes = 1;
1839
1840                 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
1841                 g_assert (table);
1842
1843                 table->num_holes = (guint16)num_holes;
1844                 for (i = 0; i < num_holes; ++i) {
1845                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
1846                         hole->clause = decode_value (p, &p);
1847                         hole->length = decode_value (p, &p);
1848                         hole->offset = decode_value (p, &p);
1849                 }
1850         }
1851
1852         if (has_seq_points) {
1853                 MonoSeqPointInfo *seq_points;
1854                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
1855
1856                 int len = decode_value (p, &p);
1857
1858                 seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
1859                 seq_points->len = len;
1860                 last_il_offset = last_native_offset = 0;
1861                 for (i = 0; i < len; ++i) {
1862                         SeqPoint *sp = &seq_points->seq_points [i];
1863                         il_offset = last_il_offset + decode_value (p, &p);
1864                         native_offset = last_native_offset + decode_value (p, &p);
1865
1866                         sp->il_offset = il_offset;
1867                         sp->native_offset = native_offset;
1868                         
1869                         sp->next_len = decode_value (p, &p);
1870                         sp->next = g_new (int, sp->next_len);
1871                         for (j = 0; j < sp->next_len; ++j)
1872                                 sp->next [j] = decode_value (p, &p);
1873
1874                         last_il_offset = il_offset;
1875                         last_native_offset = native_offset;
1876                 }
1877
1878                 mono_domain_lock (domain);
1879                 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
1880                 mono_domain_unlock (domain);
1881         }
1882
1883         /* Load debug info */
1884         buf_len = decode_value (p, &p);
1885         mono_debug_add_aot_method (domain, method, code, p, buf_len);
1886
1887         if (amodule != jinfo->method->klass->image->aot_module) {
1888                 mono_aot_lock ();
1889                 if (!ji_to_amodule)
1890                         ji_to_amodule = g_hash_table_new (NULL, NULL);
1891                 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
1892                 mono_aot_unlock ();             
1893         }
1894         
1895         return jinfo;
1896 }
1897
1898 /*
1899  * mono_aot_get_unwind_info:
1900  *
1901  *   Return a pointer to the DWARF unwind info belonging to JI.
1902  */
1903 guint8*
1904 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
1905 {
1906         MonoAotModule *amodule = ji->method->klass->image->aot_module;
1907         guint8 *p;
1908         guint8 *code = ji->code_start;
1909
1910         g_assert (amodule);
1911         g_assert (ji->from_aot);
1912
1913         if (!(code >= amodule->code && code <= amodule->code_end)) {
1914                 /* ji belongs to a different aot module than amodule */
1915                 mono_aot_lock ();
1916                 g_assert (ji_to_amodule);
1917                 amodule = g_hash_table_lookup (ji_to_amodule, ji);
1918                 g_assert (amodule);
1919                 g_assert (code >= amodule->code && code <= amodule->code_end);
1920                 mono_aot_unlock ();
1921         }
1922
1923         p = amodule->unwind_info + ji->used_regs;
1924         *unwind_info_len = decode_value (p, &p);
1925         return p;
1926 }
1927
1928 static G_GNUC_UNUSED int
1929 compare_ints (const void *a, const void *b)
1930 {
1931         return *(gint32*)a - *(gint32*)b;
1932 }
1933
1934 static void
1935 msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch)
1936 {
1937         int mid = (lo + hi) / 2;
1938         int i, t_lo, t_hi;
1939
1940         if (lo >= hi)
1941                 return;
1942
1943         if (hi - lo < 32) {
1944                 for (i = lo; i < hi; ++i)
1945                         if (array [(i * 2)] > array [(i * 2) + 2])
1946                                 break;
1947                 if (i == hi)
1948                         /* Already sorted */
1949                         return;
1950         }
1951
1952         msort_code_offsets_internal (array, lo, mid, scratch);
1953         msort_code_offsets_internal (array, mid + 1, hi, scratch);
1954
1955         if (array [mid * 2] < array [(mid + 1) * 2])
1956                 return;
1957
1958         /* Merge */
1959         t_lo = lo;
1960         t_hi = mid + 1;
1961         for (i = lo; i <= hi; i ++) {
1962                 if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) {
1963                         scratch [(i * 2)] = array [t_lo * 2];
1964                         scratch [(i * 2) + 1] = array [(t_lo *2) + 1];
1965                         t_lo ++;
1966                 } else {
1967                         scratch [(i * 2)] = array [t_hi * 2];
1968                         scratch [(i * 2) + 1] = array [(t_hi *2) + 1];
1969                         t_hi ++;
1970                 }
1971         }
1972         for (i = lo; i <= hi; ++i) {
1973                 array [(i * 2)] = scratch [i * 2];
1974                 array [(i * 2) + 1] = scratch [(i * 2) + 1];
1975         }
1976 }
1977
1978 static void
1979 msort_code_offsets (gint32 *array, int len)
1980 {
1981         gint32 *scratch;
1982
1983         scratch = g_new (gint32, len * 2);
1984         msort_code_offsets_internal (array, 0, len - 1, scratch);
1985         g_free (scratch);
1986 }
1987
1988 MonoJitInfo *
1989 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
1990 {
1991         int pos, left, right, offset, offset1, offset2, code_len;
1992         int method_index, table_len, is_wrapper;
1993         guint32 token;
1994         MonoAotModule *amodule = image->aot_module;
1995         MonoMethod *method;
1996         MonoJitInfo *jinfo;
1997         guint8 *code, *ex_info, *p;
1998         guint32 *table;
1999         int nmethods = amodule->info.nmethods;
2000         gint32 *code_offsets;
2001         int offsets_len, i;
2002
2003         if (!amodule)
2004                 return NULL;
2005
2006         if (domain != mono_get_root_domain ())
2007                 /* FIXME: */
2008                 return NULL;
2009
2010         offset = (guint8*)addr - amodule->code;
2011
2012         /* Compute a sorted table mapping code offsets to method indexes. */
2013         if (!amodule->sorted_code_offsets) {
2014
2015                 code_offsets = g_new0 (gint32, nmethods * 2);
2016                 offsets_len = 0;
2017                 for (i = 0; i < nmethods; ++i) {
2018                         /* Skip the -1 entries to speed up sorting */
2019                         if (amodule->code_offsets [i] == 0xffffffff)
2020                                 continue;
2021                         code_offsets [(offsets_len * 2)] = amodule->code_offsets [i];
2022                         code_offsets [(offsets_len *2) + 1] = i;
2023                         offsets_len ++;
2024                 }
2025                 /* Use a merge sort as this is mostly sorted */
2026                 msort_code_offsets (code_offsets, offsets_len);
2027                 //qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints);
2028                 for (i = 0; i < offsets_len -1; ++i)
2029                         g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);
2030
2031                 if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
2032                         /* Somebody got in before us */
2033                         g_free (code_offsets);
2034                 amodule->sorted_code_offsets_len = offsets_len;
2035         }
2036
2037         code_offsets = amodule->sorted_code_offsets;
2038         offsets_len = amodule->sorted_code_offsets_len;
2039
2040         /* Binary search in the sorted_code_offsets table */
2041         left = 0;
2042         right = offsets_len;
2043         while (TRUE) {
2044                 pos = (left + right) / 2;
2045
2046                 offset1 = code_offsets [(pos * 2)];
2047                 if (pos + 1 == offsets_len)
2048                         offset2 = amodule->code_end - amodule->code;
2049                 else
2050                         offset2 = code_offsets [(pos + 1) * 2];
2051
2052                 if (offset < offset1)
2053                         right = pos;
2054                 else if (offset >= offset2)
2055                         left = pos + 1;
2056                 else
2057                         break;
2058         }
2059
2060         g_assert (offset >= code_offsets [(pos * 2)]);
2061         if (pos + 1 < offsets_len)
2062                 g_assert (offset < code_offsets [((pos + 1) * 2)]);
2063         method_index = code_offsets [(pos * 2) + 1];
2064
2065         code = &amodule->code [amodule->code_offsets [method_index]];
2066         ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
2067
2068         if (pos == offsets_len - 1)
2069                 code_len = amodule->code_end - code;
2070         else
2071                 code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];
2072
2073         g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
2074
2075         /* Might be a wrapper/extra method */
2076         if (amodule->extra_methods) {
2077                 mono_aot_lock ();
2078                 method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
2079                 mono_aot_unlock ();
2080         } else {
2081                 method = NULL;
2082         }
2083
2084         if (!method) {
2085                 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
2086                         /* 
2087                          * This is hit for extra methods which are called directly, so they are
2088                          * not in amodule->extra_methods.
2089                          */
2090                         table_len = amodule->extra_method_info_offsets [0];
2091                         table = amodule->extra_method_info_offsets + 1;
2092                         left = 0;
2093                         right = table_len;
2094                         pos = 0;
2095
2096                         /* Binary search */
2097                         while (TRUE) {
2098                                 pos = ((left + right) / 2);
2099
2100                                 g_assert (pos < table_len);
2101
2102                                 if (table [pos * 2] < method_index)
2103                                         left = pos + 1;
2104                                 else if (table [pos * 2] > method_index)
2105                                         right = pos;
2106                                 else
2107                                         break;
2108                         }
2109
2110                         p = amodule->blob + table [(pos * 2) + 1];
2111                         is_wrapper = decode_value (p, &p);
2112                         g_assert (!is_wrapper);
2113                         method = decode_resolve_method_ref (amodule, p, &p);
2114                         g_assert (method);
2115                 } else {
2116                         token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
2117                         method = mono_get_method (image, token, NULL);
2118                 }
2119         }
2120
2121         /* FIXME: */
2122         g_assert (method);
2123
2124         //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2125         
2126         jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);
2127
2128         g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
2129         g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
2130
2131         /* Add it to the normal JitInfo tables */
2132         mono_jit_info_table_add (domain, jinfo);
2133         
2134         return jinfo;
2135 }
2136
2137 static gboolean
2138 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
2139 {
2140         guint8 *p = buf;
2141         gpointer *table;
2142         MonoImage *image;
2143         int i;
2144
2145         switch (ji->type) {
2146         case MONO_PATCH_INFO_METHOD:
2147         case MONO_PATCH_INFO_METHOD_JUMP:
2148         case MONO_PATCH_INFO_ICALL_ADDR:
2149         case MONO_PATCH_INFO_METHOD_RGCTX: {
2150                 MethodRef ref;
2151                 gboolean res;
2152
2153                 res = decode_method_ref (aot_module, &ref, p, &p);
2154                 if (!res)
2155                         goto cleanup;
2156
2157                 if (!ref.method && !mono_aot_only && !ref.no_aot_trampoline && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (ref.token) == MONO_TABLE_METHOD)) {
2158                         ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (ref.image, ref.token));
2159                         ji->type = MONO_PATCH_INFO_ABS;
2160                 }
2161                 else {
2162                         if (ref.method)
2163                                 ji->data.method = ref.method;
2164                         else
2165                                 ji->data.method = mono_get_method (ref.image, ref.token, NULL);
2166                         g_assert (ji->data.method);
2167                         mono_class_init (ji->data.method->klass);
2168                 }
2169                 break;
2170         }
2171         case MONO_PATCH_INFO_INTERNAL_METHOD:
2172         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2173                 guint32 len = decode_value (p, &p);
2174
2175                 ji->data.name = (char*)p;
2176                 p += len + 1;
2177                 break;
2178         }
2179         case MONO_PATCH_INFO_METHODCONST:
2180                 /* Shared */
2181                 ji->data.method = decode_resolve_method_ref (aot_module, p, &p);
2182                 if (!ji->data.method)
2183                         goto cleanup;
2184                 break;
2185         case MONO_PATCH_INFO_VTABLE:
2186         case MONO_PATCH_INFO_CLASS:
2187         case MONO_PATCH_INFO_IID:
2188         case MONO_PATCH_INFO_ADJUSTED_IID:
2189                 /* Shared */
2190                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2191                 if (!ji->data.klass)
2192                         goto cleanup;
2193                 break;
2194         case MONO_PATCH_INFO_CLASS_INIT:
2195         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2196                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2197                 if (!ji->data.klass)
2198                         goto cleanup;
2199                 break;
2200         case MONO_PATCH_INFO_IMAGE:
2201                 ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE);
2202                 if (!ji->data.image)
2203                         goto cleanup;
2204                 break;
2205         case MONO_PATCH_INFO_FIELD:
2206         case MONO_PATCH_INFO_SFLDA:
2207                 /* Shared */
2208                 ji->data.field = decode_field_info (aot_module, p, &p);
2209                 if (!ji->data.field)
2210                         goto cleanup;
2211                 break;
2212         case MONO_PATCH_INFO_SWITCH:
2213                 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
2214                 ji->data.table->table_size = decode_value (p, &p);
2215                 table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
2216                 ji->data.table->table = (MonoBasicBlock**)table;
2217                 for (i = 0; i < ji->data.table->table_size; i++)
2218                         table [i] = (gpointer)(gssize)decode_value (p, &p);
2219                 break;
2220         case MONO_PATCH_INFO_R4: {
2221                 guint32 val;
2222                 
2223                 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
2224                 val = decode_value (p, &p);
2225                 *(float*)ji->data.target = *(float*)&val;
2226                 break;
2227         }
2228         case MONO_PATCH_INFO_R8: {
2229                 guint32 val [2];
2230                 guint64 v;
2231
2232                 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
2233
2234                 val [0] = decode_value (p, &p);
2235                 val [1] = decode_value (p, &p);
2236                 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
2237                 *(double*)ji->data.target = *(double*)&v;
2238                 break;
2239         }
2240         case MONO_PATCH_INFO_LDSTR:
2241                 image = load_image (aot_module, decode_value (p, &p), TRUE);
2242                 if (!image)
2243                         goto cleanup;
2244                 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
2245                 break;
2246         case MONO_PATCH_INFO_RVA:
2247         case MONO_PATCH_INFO_DECLSEC:
2248         case MONO_PATCH_INFO_LDTOKEN:
2249         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2250                 /* Shared */
2251                 image = load_image (aot_module, decode_value (p, &p), TRUE);
2252                 if (!image)
2253                         goto cleanup;
2254                 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
2255
2256                 ji->data.token->has_context = decode_value (p, &p);
2257                 if (ji->data.token->has_context) {
2258                         gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
2259                         if (!res)
2260                                 goto cleanup;
2261                 }
2262                 break;
2263         case MONO_PATCH_INFO_EXC_NAME:
2264                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2265                 if (!ji->data.klass)
2266                         goto cleanup;
2267                 ji->data.name = ji->data.klass->name;
2268                 break;
2269         case MONO_PATCH_INFO_METHOD_REL:
2270                 ji->data.offset = decode_value (p, &p);
2271                 break;
2272         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2273         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2274         case MONO_PATCH_INFO_MONITOR_ENTER:
2275         case MONO_PATCH_INFO_MONITOR_EXIT:
2276         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
2277                 break;
2278         case MONO_PATCH_INFO_RGCTX_FETCH: {
2279                 gboolean res;
2280                 MonoJumpInfoRgctxEntry *entry;
2281
2282                 entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
2283                 entry->method = decode_resolve_method_ref (aot_module, p, &p);
2284                 entry->in_mrgctx = decode_value (p, &p);
2285                 entry->info_type = decode_value (p, &p);
2286                 entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
2287                 entry->data->type = decode_value (p, &p);
2288                 
2289                 res = decode_patch (aot_module, mp, entry->data, p, &p);
2290                 if (!res)
2291                         goto cleanup;
2292                 ji->data.rgctx_entry = entry;
2293                 break;
2294         }
2295         case MONO_PATCH_INFO_SEQ_POINT_INFO:
2296                 break;
2297         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
2298                 MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));
2299
2300                 imt_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
2301                 imt_tramp->vt_offset = decode_value (p, &p);
2302                 
2303                 ji->data.imt_tramp = imt_tramp;
2304                 break;
2305         }
2306         default:
2307                 g_warning ("unhandled type %d", ji->type);
2308                 g_assert_not_reached ();
2309         }
2310
2311         *endbuf = p;
2312
2313         return TRUE;
2314
2315  cleanup:
2316         return FALSE;
2317 }
2318
2319 static MonoJumpInfo*
2320 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches, 
2321                                  guint32 **got_slots, 
2322                                  guint8 *buf, guint8 **endbuf)
2323 {
2324         MonoJumpInfo *patches;
2325         int pindex;
2326         guint8 *p;
2327
2328         p = buf;
2329
2330         patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
2331
2332         *got_slots = g_malloc (sizeof (guint32) * n_patches);
2333
2334         for (pindex = 0; pindex < n_patches; ++pindex) {
2335                 MonoJumpInfo *ji = &patches [pindex];
2336                 guint8 *shared_p;
2337                 gboolean res;
2338                 guint32 got_offset;
2339
2340                 got_offset = decode_value (p, &p);
2341
2342                 if (aot_module->got [got_offset]) {
2343                         /* Already loaded */
2344                         //printf ("HIT!\n");
2345                 } else {
2346                         shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);
2347
2348                         ji->type = decode_value (shared_p, &shared_p);
2349
2350                         res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
2351                         if (!res)
2352                                 goto cleanup;
2353                 }
2354
2355                 (*got_slots) [pindex] = got_offset;
2356         }
2357
2358         *endbuf = p;
2359         return patches;
2360
2361  cleanup:
2362         g_free (*got_slots);
2363         *got_slots = NULL;
2364
2365         return NULL;
2366 }
2367
2368 static void
2369 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
2370 {
2371         /*
2372          * Jump addresses cannot be patched by the trampoline code since it
2373          * does not have access to the caller's address. Instead, we collect
2374          * the addresses of the GOT slots pointing to a method, and patch
2375          * them after the method has been compiled.
2376          */
2377         MonoJitDomainInfo *info = domain_jit_info (domain);
2378         GSList *list;
2379                 
2380         mono_domain_lock (domain);
2381         if (!info->jump_target_got_slot_hash)
2382                 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
2383         list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
2384         list = g_slist_prepend (list, got_slot);
2385         g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
2386         mono_domain_unlock (domain);
2387 }
2388
2389 /*
2390  * load_method:
2391  *
2392  *   Load the method identified by METHOD_INDEX from the AOT image. Return a
2393  * pointer to the native code of the method, or NULL if not found.
2394  * METHOD might not be set if the caller only has the image/token info.
2395  */
2396 static gpointer
2397 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
2398 {
2399         MonoClass *klass;
2400         gboolean from_plt = method == NULL;
2401         MonoMemPool *mp;
2402         int i, pindex, n_patches, used_strings;
2403         gboolean keep_patches = TRUE;
2404         guint8 *p;
2405         MonoJitInfo *jinfo = NULL;
2406         guint8 *code, *info;
2407
2408         if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
2409                 return NULL;
2410
2411         if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
2412                 /* Non shared AOT code can't be used in other appdomains */
2413                 return NULL;
2414
2415         if (amodule->out_of_date)
2416                 return NULL;
2417
2418         if (amodule->code_offsets [method_index] == 0xffffffff) {
2419                 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2420                         char *full_name;
2421
2422                         if (!method)
2423                                 method = mono_get_method (image, token, NULL);
2424                         full_name = mono_method_full_name (method, TRUE);
2425                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
2426                         g_free (full_name);
2427                 }
2428                 return NULL;
2429         }
2430
2431         code = &amodule->code [amodule->code_offsets [method_index]];
2432
2433         info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
2434
2435         mono_aot_lock ();
2436         if (!amodule->methods_loaded)
2437                 amodule->methods_loaded = g_new0 (guint32, amodule->info.nmethods + 1);
2438         mono_aot_unlock ();
2439
2440         if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
2441                 return code;
2442
2443         if (mono_last_aot_method != -1) {
2444                 if (mono_jit_stats.methods_aot >= mono_last_aot_method)
2445                                 return NULL;
2446                 else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
2447                         if (!method)
2448                                 method = mono_get_method (image, token, NULL);
2449                         if (method) {
2450                                 char *name = mono_method_full_name (method, TRUE);
2451                                 printf ("LAST AOT METHOD: %s.\n", name);
2452                                 g_free (name);
2453                         } else {
2454                                 printf ("LAST AOT METHOD: %p %d\n", code, method_index);
2455                         }
2456                 }
2457         }
2458
2459         p = info;
2460
2461         if (method) {
2462                 klass = method->klass;
2463                 decode_klass_ref (amodule, p, &p);
2464         } else {
2465                 klass = decode_klass_ref (amodule, p, &p);
2466         }
2467
2468         if (amodule->info.opts & MONO_OPT_SHARED)
2469                 used_strings = decode_value (p, &p);
2470         else
2471                 used_strings = 0;
2472
2473         for (i = 0; i < used_strings; i++) {
2474                 guint token = decode_value (p, &p);
2475                 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
2476         }
2477
2478         if (amodule->info.opts & MONO_OPT_SHARED)       
2479                 keep_patches = FALSE;
2480
2481         n_patches = decode_value (p, &p);
2482
2483         keep_patches = FALSE;
2484
2485         if (n_patches) {
2486                 MonoJumpInfo *patches;
2487                 guint32 *got_slots;
2488
2489                 if (keep_patches)
2490                         mp = domain->mp;
2491                 else
2492                         mp = mono_mempool_new ();
2493
2494                 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
2495                 if (patches == NULL)
2496                         goto cleanup;
2497
2498                 for (pindex = 0; pindex < n_patches; ++pindex) {
2499                         MonoJumpInfo *ji = &patches [pindex];
2500
2501                         if (!amodule->got [got_slots [pindex]]) {
2502                                 amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
2503                                 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
2504                                         amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
2505                                 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
2506                                         register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
2507                         }
2508                         ji->type = MONO_PATCH_INFO_NONE;
2509                 }
2510
2511                 g_free (got_slots);
2512
2513                 if (!keep_patches)
2514                         mono_mempool_destroy (mp);
2515         }
2516
2517         if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2518                 char *full_name;
2519
2520                 if (!method)
2521                         method = mono_get_method (image, token, NULL);
2522
2523                 full_name = mono_method_full_name (method, TRUE);
2524
2525                 if (!jinfo)
2526                         jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
2527
2528                 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);
2529                 g_free (full_name);
2530         }
2531
2532         mono_aot_lock ();
2533
2534         mono_jit_stats.methods_aot++;
2535
2536         amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
2537
2538         init_plt (amodule);
2539
2540         if (method && method->wrapper_type)
2541                 g_hash_table_insert (amodule->method_to_code, method, code);
2542
2543         mono_aot_unlock ();
2544
2545         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
2546                 MonoJitInfo *jinfo;
2547
2548                 if (!method) {
2549                         method = mono_get_method (image, token, NULL);
2550                         g_assert (method);
2551                 }
2552                 mono_profiler_method_jit (method);
2553                 jinfo = mono_jit_info_table_find (domain, (char*)code);
2554                 g_assert (jinfo);
2555                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
2556         }
2557
2558         if (from_plt && klass && !klass->generic_container)
2559                 mono_runtime_class_init (mono_class_vtable (domain, klass));
2560
2561         return code;
2562
2563  cleanup:
2564         /* FIXME: The space in domain->mp is wasted */  
2565         if (amodule->info.opts & MONO_OPT_SHARED)
2566                 /* No need to cache patches */
2567                 mono_mempool_destroy (mp);
2568
2569         if (jinfo)
2570                 g_free (jinfo);
2571
2572         return NULL;
2573 }
2574
2575 static guint32
2576 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method, const char *name)
2577 {
2578         guint32 table_size, entry_size, hash;
2579         guint32 *table, *entry;
2580         guint32 index;
2581         static guint32 n_extra_decodes;
2582
2583         if (!amodule)
2584                 return 0xffffff;
2585
2586         table_size = amodule->extra_method_table [0];
2587         table = amodule->extra_method_table + 1;
2588         entry_size = 3;
2589
2590         hash = mono_aot_method_hash (method) % table_size;
2591
2592         entry = &table [hash * entry_size];
2593
2594         if (entry [0] == 0)
2595                 return 0xffffff;
2596
2597         index = 0xffffff;
2598         while (TRUE) {
2599                 guint32 key = entry [0];
2600                 guint32 value = entry [1];
2601                 guint32 next = entry [entry_size - 1];
2602                 MonoMethod *m;
2603                 guint8 *p;
2604                 int is_wrapper_name;
2605
2606                 p = amodule->blob + key;
2607                 is_wrapper_name = decode_value (p, &p);
2608                 if (is_wrapper_name) {
2609                         int wrapper_type = decode_value (p, &p);
2610                         if (wrapper_type == method->wrapper_type && !strcmp (name, (char*)p)) {
2611                                 index = value;
2612                                 break;
2613                         }
2614                 } else {
2615                         guint8 *orig_p = p;
2616
2617                         mono_aot_lock ();
2618                         if (!amodule->method_ref_to_method)
2619                                 amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
2620                         m = g_hash_table_lookup (amodule->method_ref_to_method, p);
2621                         mono_aot_unlock ();
2622                         if (!m) {
2623                                 m = decode_resolve_method_ref_with_target (amodule, method, p, &p);
2624                                 if (m) {
2625                                         mono_aot_lock ();
2626                                         g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
2627                                         mono_aot_unlock ();
2628                                 }
2629                         }
2630                         if (m == method) {
2631                                 index = value;
2632                                 break;
2633                         }
2634
2635                         /* Special case: wrappers of shared generic methods */
2636                         if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
2637                                 method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
2638                                 MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
2639                                 MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
2640
2641                                 if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
2642                                         index = value;
2643                                         break;
2644                                 }
2645                         }
2646
2647                         /* Methods decoded needlessly */
2648                         if (m) {
2649                                 //printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
2650                                 n_extra_decodes ++;
2651                         }
2652                 }
2653
2654                 if (next != 0)
2655                         entry = &table [next * entry_size];
2656                 else
2657                         break;
2658         }
2659
2660         return index;
2661 }
2662
2663 static void
2664 add_module_cb (gpointer key, gpointer value, gpointer user_data)
2665 {
2666         g_ptr_array_add ((GPtrArray*)user_data, value);
2667 }
2668
2669 /*
2670  * find_extra_method:
2671  *
2672  *   Try finding METHOD in the extra_method table in all AOT images.
2673  * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
2674  * module where the method was found.
2675  */
2676 static guint32
2677 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
2678 {
2679         guint32 index;
2680         GPtrArray *modules;
2681         int i;
2682         char *name = NULL;
2683
2684         if (method->wrapper_type)
2685                 name = mono_aot_wrapper_name (method);
2686
2687         /* Try the method's module first */
2688         *out_amodule = method->klass->image->aot_module;
2689         index = find_extra_method_in_amodule (method->klass->image->aot_module, method, name);
2690         if (index != 0xffffff) {
2691                 g_free (name);
2692                 return index;
2693         }
2694
2695         /* 
2696          * Try all other modules.
2697          * This is needed because generic instances klass->image points to the image
2698          * containing the generic definition, but the native code is generated to the
2699          * AOT image which contains the reference.
2700          */
2701
2702         /* Make a copy to avoid doing the search inside the aot lock */
2703         modules = g_ptr_array_new ();
2704         mono_aot_lock ();
2705         g_hash_table_foreach (aot_modules, add_module_cb, modules);
2706         mono_aot_unlock ();
2707
2708         index = 0xffffff;
2709         for (i = 0; i < modules->len; ++i) {
2710                 MonoAotModule *amodule = g_ptr_array_index (modules, i);
2711
2712                 if (amodule != method->klass->image->aot_module)
2713                         index = find_extra_method_in_amodule (amodule, method, name);
2714                 if (index != 0xffffff) {
2715                         *out_amodule = amodule;
2716                         break;
2717                 }
2718         }
2719         
2720         g_ptr_array_free (modules, TRUE);
2721
2722         g_free (name);
2723         return index;
2724 }
2725
2726 /*
2727  * mono_aot_get_method:
2728  *
2729  *   Return a pointer to the AOTed native code for METHOD if it can be found,
2730  * NULL otherwise.
2731  * On platforms with function pointers, this doesn't return a function pointer.
2732  */
2733 gpointer
2734 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
2735 {
2736         MonoClass *klass = method->klass;
2737         guint32 method_index;
2738         MonoAotModule *amodule = klass->image->aot_module;
2739         guint8 *code;
2740
2741         if (!amodule)
2742                 return NULL;
2743
2744         if (amodule->out_of_date)
2745                 return NULL;
2746
2747         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2748                 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2749                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2750                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2751                 return NULL;
2752
2753         /*
2754          * Use the original method instead of its invoke-with-check wrapper.
2755          * This is not a problem when using full-aot, since it doesn't support
2756          * remoting.
2757          */
2758         if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
2759                 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));
2760
2761         g_assert (klass->inited);
2762
2763         /* Find method index */
2764         if (method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE)) {
2765                 /* 
2766                  * For generic methods, we store the fully shared instance in place of the
2767                  * original method.
2768                  */
2769                 method = mono_method_get_declaring_generic_method (method);
2770                 method_index = mono_metadata_token_index (method->token) - 1;
2771         } else if (method->is_inflated || !method->token) {
2772                 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
2773                 mono_aot_lock ();
2774                 code = g_hash_table_lookup (amodule->method_to_code, method);
2775                 mono_aot_unlock ();
2776                 if (code)
2777                         return code;
2778
2779                 method_index = find_extra_method (method, &amodule);
2780                 /*
2781                  * Special case the ICollection<T> wrappers for arrays, as they cannot
2782                  * be statically enumerated, and each wrapper ends up calling the same
2783                  * method in Array.
2784                  */
2785                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
2786                         MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2787
2788                         code = mono_aot_get_method (domain, m);
2789                         if (code) {
2790                                 if (mono_method_needs_static_rgctx_invoke (m, FALSE)) {
2791                                         code = mono_create_static_rgctx_trampoline (m, mono_create_ftnptr (domain, code));
2792                                         /* The call above returns an ftnptr */
2793                                         code = mono_get_addr_from_ftnptr (code);
2794                                 }
2795
2796                                 return code;
2797                         }
2798                 }
2799
2800                 /*
2801                  * Special case Array.GetGenericValueImpl which is a generic icall.
2802                  * Generic sharing currently can't handle it, but the icall returns data using
2803                  * an out parameter, so the managed-to-native wrappers can share the same code.
2804                  */
2805                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
2806                         MonoMethod *m;
2807                         MonoGenericContext ctx;
2808                         MonoType *args [16];
2809
2810                         if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
2811                                 /* Avoid recursion */
2812                                 return NULL;
2813
2814                         m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
2815                         g_assert (m);
2816
2817                         memset (&ctx, 0, sizeof (ctx));
2818                         args [0] = &mono_defaults.object_class->byval_arg;
2819                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2820
2821                         m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
2822
2823                         /* 
2824                          * Get the code for the <object> instantiation which should be emitted into
2825                          * the mscorlib aot image by the AOT compiler.
2826                          */
2827                         code = mono_aot_get_method (domain, m);
2828                         if (code)
2829                                 return code;
2830                 }
2831
2832                 /* Same for CompareExchange<T> */
2833                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass->image == mono_defaults.corlib && !strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Interlocked") && !strcmp (method->name, "CompareExchange")) {
2834                         MonoMethod *m;
2835                         MonoGenericContext ctx;
2836                         MonoType *args [16];
2837                         gpointer iter = NULL;
2838
2839                         while ((m = mono_class_get_methods (method->klass, &iter))) {
2840                                 if (mono_method_signature (m)->generic_param_count && !strcmp (m->name, "CompareExchange"))
2841                                         break;
2842                         }
2843                         g_assert (m);
2844
2845                         memset (&ctx, 0, sizeof (ctx));
2846                         args [0] = &mono_defaults.object_class->byval_arg;
2847                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2848
2849                         m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
2850
2851                         /* Avoid recursion */
2852                         if (method == m)
2853                                 return NULL;
2854
2855                         /* 
2856                          * Get the code for the <object> instantiation which should be emitted into
2857                          * the mscorlib aot image by the AOT compiler.
2858                          */
2859                         code = mono_aot_get_method (domain, m);
2860                         if (code)
2861                                 return code;
2862                 }
2863
2864                 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, TRUE)) {
2865                         /* Partial sharing */
2866                         method_index = find_extra_method (mini_get_shared_method (method), &amodule);
2867                 }
2868
2869                 if (method_index == 0xffffff) {
2870                         if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2871                                 char *full_name;
2872
2873                                 full_name = mono_method_full_name (method, TRUE);
2874                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
2875                                 g_free (full_name);
2876                         }
2877                         return NULL;
2878                 }
2879
2880                 if (method_index == 0xffffff)
2881                         return NULL;
2882
2883                 /* Needed by find_jit_info */
2884                 mono_aot_lock ();
2885                 if (!amodule->extra_methods)
2886                         amodule->extra_methods = g_hash_table_new (NULL, NULL);
2887                 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
2888                 mono_aot_unlock ();
2889         } else {
2890                 /* Common case */
2891                 method_index = mono_metadata_token_index (method->token) - 1;
2892         }
2893
2894         return load_method (domain, amodule, klass->image, method, method->token, method_index);
2895 }
2896
2897 /**
2898  * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
2899  * method.
2900  */
2901 gpointer
2902 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
2903 {
2904         MonoAotModule *aot_module = image->aot_module;
2905         int method_index;
2906
2907         if (!aot_module)
2908                 return NULL;
2909
2910         method_index = mono_metadata_token_index (token) - 1;
2911
2912         return load_method (domain, aot_module, image, NULL, token, method_index);
2913 }
2914
2915 typedef struct {
2916         guint8 *addr;
2917         gboolean res;
2918 } IsGotEntryUserData;
2919
2920 static void
2921 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
2922 {
2923         IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
2924         MonoAotModule *aot_module = (MonoAotModule*)value;
2925
2926         if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
2927                 data->res = TRUE;
2928 }
2929
2930 gboolean
2931 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
2932 {
2933         IsGotEntryUserData user_data;
2934
2935         if (!aot_modules)
2936                 return FALSE;
2937
2938         user_data.addr = addr;
2939         user_data.res = FALSE;
2940         mono_aot_lock ();
2941         g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
2942         mono_aot_unlock ();
2943         
2944         return user_data.res;
2945 }
2946
2947 typedef struct {
2948         guint8 *addr;
2949         MonoAotModule *module;
2950 } FindAotModuleUserData;
2951
2952 static void
2953 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
2954 {
2955         FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
2956         MonoAotModule *aot_module = (MonoAotModule*)value;
2957
2958         if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
2959                 data->module = aot_module;
2960 }
2961
2962 static inline MonoAotModule*
2963 find_aot_module (guint8 *code)
2964 {
2965         FindAotModuleUserData user_data;
2966
2967         if (!aot_modules)
2968                 return NULL;
2969
2970         /* Reading these need no locking */
2971         if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
2972                 return NULL;
2973
2974         user_data.addr = code;
2975         user_data.module = NULL;
2976                 
2977         mono_aot_lock ();
2978         g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
2979         mono_aot_unlock ();
2980         
2981         return user_data.module;
2982 }
2983
2984 void
2985 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
2986 {
2987         /*
2988          * Since AOT code is only used in the root domain, 
2989          * mono_domain_get () != mono_get_root_domain () means the calling method
2990          * is AppDomain:InvokeInDomain, so this is the same check as in 
2991          * mono_method_same_domain () but without loading the metadata for the method.
2992          */
2993         if (mono_domain_get () == mono_get_root_domain ())
2994                 mono_arch_patch_plt_entry (code, got, regs, addr);
2995 }
2996
2997 /*
2998  * mono_aot_plt_resolve:
2999  *
3000  *   This function is called by the entries in the PLT to resolve the actual method that
3001  * needs to be called. It returns a trampoline to the method and patches the PLT entry.
3002  * Returns NULL if the something cannot be loaded.
3003  */
3004 gpointer
3005 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3006 {
3007 #ifdef MONO_ARCH_AOT_SUPPORTED
3008         guint8 *p, *target, *plt_entry;
3009         MonoJumpInfo ji;
3010         MonoAotModule *module = (MonoAotModule*)aot_module;
3011         gboolean res, no_ftnptr = FALSE;
3012         MonoMemPool *mp;
3013
3014         //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
3015
3016         p = &module->blob [plt_info_offset];
3017
3018         ji.type = decode_value (p, &p);
3019
3020         mp = mono_mempool_new_size (512);
3021         res = decode_patch (module, mp, &ji, p, &p);
3022
3023         if (!res) {
3024                 mono_mempool_destroy (mp);
3025                 return NULL;
3026         }
3027
3028         /* 
3029          * Avoid calling resolve_patch_target in the full-aot case if possible, since
3030          * it would create a trampoline, and we don't need that.
3031          * We could do this only if the method does not need the special handling
3032          * in mono_magic_trampoline ().
3033          */
3034         if (mono_aot_only && ji.type == MONO_PATCH_INFO_METHOD && !ji.data.method->is_generic && !mono_method_check_context_used (ji.data.method) && !(ji.data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) &&
3035                 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE)) {
3036                 target = mono_jit_compile_method (ji.data.method);
3037                 no_ftnptr = TRUE;
3038         } else {
3039                 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
3040         }
3041
3042         /*
3043          * The trampoline expects us to return a function descriptor on platforms which use
3044          * it, but resolve_patch_target returns a direct function pointer for some type of
3045          * patches, so have to translate between the two.
3046          * FIXME: Clean this up, but how ?
3047          */
3048         if (ji.type == MONO_PATCH_INFO_ABS || ji.type == MONO_PATCH_INFO_INTERNAL_METHOD || ji.type == MONO_PATCH_INFO_CLASS_INIT || ji.type == MONO_PATCH_INFO_ICALL_ADDR || ji.type == MONO_PATCH_INFO_JIT_ICALL_ADDR || ji.type == MONO_PATCH_INFO_RGCTX_FETCH) {
3049                 /* These should already have a function descriptor */
3050 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3051                 /* Our function descriptors have a 0 environment, gcc created ones don't */
3052                 if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
3053                         g_assert (((gpointer*)target) [2] == 0);
3054 #endif
3055                 /* Empty */
3056         } else if (!no_ftnptr) {
3057 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3058                 g_assert (((gpointer*)target) [2] != 0);
3059 #endif
3060                 target = mono_create_ftnptr (mono_domain_get (), target);
3061         }
3062
3063         mono_mempool_destroy (mp);
3064
3065         /* Patch the PLT entry with target which might be the actual method not a trampoline */
3066         plt_entry = mono_aot_get_plt_entry (code);
3067         g_assert (plt_entry);
3068         mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target);
3069
3070         return target;
3071 #else
3072         g_assert_not_reached ();
3073         return NULL;
3074 #endif
3075 }
3076
3077 /**
3078  * init_plt:
3079  *
3080  *   Initialize the PLT table of the AOT module. Called lazily when the first AOT
3081  * method in the module is loaded to avoid committing memory by writing to it.
3082  * LOCKING: Assumes the AOT lock is held.
3083  */
3084 static void
3085 init_plt (MonoAotModule *amodule)
3086 {
3087         int i;
3088         gpointer tramp;
3089
3090         if (amodule->plt_inited)
3091                 return;
3092
3093         tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
3094
3095         /*
3096          * Initialize the PLT entries in the GOT to point to the default targets.
3097          */
3098
3099         tramp = mono_create_ftnptr (mono_domain_get (), tramp);
3100          for (i = 1; i < amodule->info.plt_size; ++i)
3101                  /* All the default entries point to the AOT trampoline */
3102                  ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
3103
3104         amodule->plt_inited = TRUE;
3105 }
3106
3107 /*
3108  * mono_aot_get_plt_entry:
3109  *
3110  *   Return the address of the PLT entry called by the code at CODE if exists.
3111  */
3112 guint8*
3113 mono_aot_get_plt_entry (guint8 *code)
3114 {
3115         MonoAotModule *aot_module = find_aot_module (code);
3116
3117         if (!aot_module)
3118                 return NULL;
3119
3120 #ifdef MONO_ARCH_AOT_SUPPORTED
3121         {
3122                 guint8 *target = mono_arch_get_call_target (code);
3123
3124                 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
3125                         return target;
3126         }
3127 #else
3128         g_assert_not_reached ();
3129 #endif
3130
3131         return NULL;
3132 }
3133
3134 /*
3135  * mono_aot_get_plt_info_offset:
3136  *
3137  *   Return the PLT info offset belonging to the plt entry called by CODE.
3138  */
3139 guint32
3140 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3141 {
3142         guint8 *plt_entry = mono_aot_get_plt_entry (code);
3143
3144         g_assert (plt_entry);
3145
3146         /* The offset is embedded inside the code after the plt entry */
3147 #ifdef MONO_ARCH_AOT_SUPPORTED
3148         return mono_arch_get_plt_info_offset (plt_entry, regs, code);
3149 #else
3150         g_assert_not_reached ();
3151         return 0;
3152 #endif
3153 }
3154
3155 static gpointer
3156 mono_create_ftnptr_malloc (guint8 *code)
3157 {
3158 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3159         MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
3160
3161         ftnptr->code = code;
3162         ftnptr->toc = NULL;
3163         ftnptr->env = NULL;
3164
3165         return ftnptr;
3166 #else
3167         return code;
3168 #endif
3169 }
3170
3171 /*
3172  * mono_aot_register_jit_icall:
3173  *
3174  *   Register a JIT icall which is called by trampolines in full-aot mode. This should
3175  * be called from mono_arch_init () during startup.
3176  */
3177 void
3178 mono_aot_register_jit_icall (const char *name, gpointer addr)
3179 {
3180         /* No need for locking */
3181         if (!aot_jit_icall_hash)
3182                 aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
3183         g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
3184 }
3185
3186 /*
3187  * load_function:
3188  *
3189  *   Load the function named NAME from the aot image. 
3190  */
3191 static gpointer
3192 load_function (MonoAotModule *amodule, const char *name)
3193 {
3194         char *symbol;
3195         guint8 *p;
3196         int n_patches, pindex;
3197         MonoMemPool *mp;
3198         gpointer code;
3199
3200         /* Load the code */
3201
3202         symbol = g_strdup_printf ("%s", name);
3203         find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
3204         g_free (symbol);
3205         if (!code)
3206                 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
3207
3208         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.\n", name, amodule->aot_name);
3209
3210         /* Load info */
3211
3212         symbol = g_strdup_printf ("%s_p", name);
3213         find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
3214         g_free (symbol);
3215         if (!p)
3216                 /* Nothing to patch */
3217                 return code;
3218
3219         p = amodule->blob + *(guint32*)p;
3220
3221         /* Similar to mono_aot_load_method () */
3222
3223         n_patches = decode_value (p, &p);
3224
3225         if (n_patches) {
3226                 MonoJumpInfo *patches;
3227                 guint32 *got_slots;
3228
3229                 mp = mono_mempool_new ();
3230
3231                 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3232                 g_assert (patches);
3233
3234                 for (pindex = 0; pindex < n_patches; ++pindex) {
3235                         MonoJumpInfo *ji = &patches [pindex];
3236                         gpointer target;
3237
3238                         if (amodule->got [got_slots [pindex]])
3239                                 continue;
3240
3241                         /*
3242                          * When this code is executed, the runtime may not be initalized yet, so
3243                          * resolve the patch info by hand.
3244                          */
3245                         if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
3246                                 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
3247                                         target = mono_get_lmf_addr;
3248                                 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
3249                                         target = mono_thread_force_interruption_checkpoint;
3250                                 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
3251                                         target = mono_exception_from_token;
3252                                 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
3253                                         target = mono_get_throw_exception ();
3254                                 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
3255                                         int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
3256                                         target = (gpointer)mono_get_trampoline_func (tramp_type2);
3257                                 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
3258                                         /* atoll is needed because the the offset is unsigned */
3259                                         guint32 slot;
3260                                         int res;
3261
3262                                         res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
3263                                         g_assert (res == 1);
3264                                         target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
3265                                         target = mono_create_ftnptr_malloc (target);
3266                                 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
3267                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
3268                                         target = mono_create_ftnptr_malloc (target);
3269                                 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
3270                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
3271                                         target = mono_create_ftnptr_malloc (target);
3272                                 } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
3273                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
3274                                         target = mono_create_ftnptr_malloc (target);
3275                                 } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
3276                                         target = mono_thread_get_and_clear_pending_exception;
3277                                 } else if (strstr (ji->data.name, "generic_trampoline_")) {
3278                                         target = mono_aot_get_trampoline (ji->data.name);
3279                                 } else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
3280                                         /* Registered by mono_arch_init () */
3281                                         target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
3282                                 } else {
3283                                         fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
3284                                         g_assert_not_reached ();
3285                                         target = NULL;
3286                                 }
3287                         } else {
3288                                 /* Hopefully the code doesn't have patches which need method or 
3289                                  * domain to be set.
3290                                  */
3291                                 target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
3292                                 g_assert (target);
3293                         }
3294
3295                         amodule->got [got_slots [pindex]] = target;
3296                 }
3297
3298                 g_free (got_slots);
3299
3300                 mono_mempool_destroy (mp);
3301         }
3302
3303         return code;
3304 }
3305
3306 /*
3307  * Return the trampoline identified by NAME from the mscorlib AOT file.
3308  * On ppc64, this returns a function descriptor.
3309  */
3310 gpointer
3311 mono_aot_get_trampoline (const char *name)
3312 {
3313         MonoImage *image;
3314         MonoAotModule *amodule;
3315
3316         image = mono_defaults.corlib;
3317         g_assert (image);
3318
3319         amodule = image->aot_module;
3320         g_assert (amodule);
3321
3322         return mono_create_ftnptr_malloc (load_function (amodule, name));
3323 }
3324
3325 /* Return a given kind of trampoline */
3326 static gpointer
3327 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
3328 {
3329         MonoAotModule *amodule;
3330         int index, tramp_size;
3331         MonoImage *image;
3332
3333         /* Currently, we keep all trampolines in the mscorlib AOT image */
3334         image = mono_defaults.corlib;
3335         g_assert (image);
3336
3337         mono_aot_lock ();
3338
3339         amodule = image->aot_module;
3340         g_assert (amodule);
3341
3342         *out_amodule = amodule;
3343
3344         if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type])
3345                 g_error ("Ran out of trampolines of type %d in '%s' (%d)\n", tramp_type, image->name, amodule->info.num_trampolines [tramp_type]);
3346
3347         index = amodule->trampoline_index [tramp_type] ++;
3348
3349         mono_aot_unlock ();
3350
3351         *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
3352
3353         tramp_size = amodule->info.trampoline_size [tramp_type];
3354
3355         if (out_tramp_size)
3356                 *out_tramp_size = tramp_size;
3357
3358         return amodule->trampolines [tramp_type] + (index * tramp_size);
3359 }
3360
3361 /*
3362  * Return a specific trampoline from the AOT file.
3363  */
3364 gpointer
3365 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
3366 {
3367         MonoAotModule *amodule;
3368         guint32 got_offset, tramp_size;
3369         guint8 *code, *tramp;
3370         static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
3371         static gboolean inited;
3372         static guint32 num_trampolines;
3373
3374         if (!inited) {
3375                 mono_aot_lock ();
3376
3377                 if (!inited) {
3378                         mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
3379                         inited = TRUE;
3380                 }
3381
3382                 mono_aot_unlock ();
3383         }
3384
3385         num_trampolines ++;
3386
3387         if (!generic_trampolines [tramp_type]) {
3388                 char *symbol;
3389
3390                 symbol = mono_get_generic_trampoline_name (tramp_type);
3391                 generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
3392                 g_free (symbol);
3393         }
3394
3395         tramp = generic_trampolines [tramp_type];
3396         g_assert (tramp);
3397
3398         code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
3399
3400         amodule->got [got_offset] = tramp;
3401         amodule->got [got_offset + 1] = arg1;
3402
3403         if (code_len)
3404                 *code_len = tramp_size;
3405
3406         return code;
3407 }
3408
3409 gpointer
3410 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
3411 {
3412         MonoAotModule *amodule;
3413         guint8 *code;
3414         guint32 got_offset;
3415
3416         code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
3417
3418         amodule->got [got_offset] = ctx;
3419         amodule->got [got_offset + 1] = addr; 
3420
3421         /* The caller expects an ftnptr */
3422         return mono_create_ftnptr (mono_domain_get (), code);
3423 }
3424
3425 gpointer
3426 mono_aot_get_unbox_trampoline (MonoMethod *method)
3427 {
3428         guint32 method_index = mono_metadata_token_index (method->token) - 1;
3429         MonoAotModule *amodule;
3430         char *symbol;
3431         gpointer code;
3432
3433         if (method->is_inflated && !mono_method_is_generic_sharable_impl (method, FALSE)) {
3434                 guint32 index = find_extra_method (method, &amodule);
3435                 g_assert (index != 0xffffff);
3436                 
3437                 symbol = g_strdup_printf ("ut_e_%d", index);
3438         } else {
3439                 amodule = method->klass->image->aot_module;
3440                 g_assert (amodule);
3441
3442                 symbol = g_strdup_printf ("ut_%d", method_index);
3443         }
3444         code = load_function (amodule, symbol);
3445         g_free (symbol);
3446
3447         /* The caller expects an ftnptr */
3448         return mono_create_ftnptr (mono_domain_get (), code);
3449 }
3450
3451 gpointer
3452 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
3453 {
3454         char *symbol;
3455         gpointer code;
3456
3457         symbol = mono_get_rgctx_fetch_trampoline_name (slot);
3458         code = load_function (mono_defaults.corlib->aot_module, symbol);
3459         g_free (symbol);
3460         /* The caller expects an ftnptr */
3461         return mono_create_ftnptr (mono_domain_get (), code);
3462 }
3463
3464 gpointer
3465 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
3466 {
3467         guint32 got_offset;
3468         gpointer code;
3469         gpointer *buf;
3470         int i;
3471         MonoAotModule *amodule;
3472
3473         code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
3474
3475         /* Save the entries into an array */
3476         buf = mono_domain_alloc (domain, (count + 1) * 2 * sizeof (gpointer));
3477         for (i = 0; i < count; ++i) {
3478                 MonoIMTCheckItem *item = imt_entries [i];               
3479
3480                 g_assert (item->key);
3481                 /* FIXME: */
3482                 g_assert (!item->has_target_code);
3483
3484                 buf [(i * 2)] = item->key;
3485                 buf [(i * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
3486         }
3487         buf [(count * 2)] = NULL;
3488         buf [(count * 2) + 1] = fail_tramp;
3489         
3490         amodule->got [got_offset] = buf;
3491
3492         return code;
3493 }
3494  
3495 /*
3496  * mono_aot_set_make_unreadable:
3497  *
3498  *   Set whenever to make all mmaped memory unreadable. In conjuction with a
3499  * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
3500  */
3501 void
3502 mono_aot_set_make_unreadable (gboolean unreadable)
3503 {
3504         static int inited;
3505
3506         make_unreadable = unreadable;
3507
3508         if (make_unreadable && !inited) {
3509                 mono_counters_register ("AOT pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
3510         }               
3511 }
3512
3513 typedef struct {
3514         MonoAotModule *module;
3515         guint8 *ptr;
3516 } FindMapUserData;
3517
3518 static void
3519 find_map (gpointer key, gpointer value, gpointer user_data)
3520 {
3521         MonoAotModule *module = (MonoAotModule*)value;
3522         FindMapUserData *data = (FindMapUserData*)user_data;
3523
3524         if (!data->module)
3525                 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
3526                         data->module = module;
3527 }
3528
3529 static MonoAotModule*
3530 find_module_for_addr (void *ptr)
3531 {
3532         FindMapUserData data;
3533
3534         if (!make_unreadable)
3535                 return NULL;
3536
3537         data.module = NULL;
3538         data.ptr = (guint8*)ptr;
3539
3540         mono_aot_lock ();
3541         g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
3542         mono_aot_unlock ();
3543
3544         return data.module;
3545 }
3546
3547 /*
3548  * mono_aot_is_pagefault:
3549  *
3550  *   Should be called from a SIGSEGV signal handler to find out whenever @ptr is
3551  * within memory allocated by this module.
3552  */
3553 gboolean
3554 mono_aot_is_pagefault (void *ptr)
3555 {
3556         if (!make_unreadable)
3557                 return FALSE;
3558
3559         /* 
3560          * Not signal safe, but SIGSEGV's are synchronous, and
3561          * this is only turned on by a MONO_DEBUG option.
3562          */
3563         return find_module_for_addr (ptr) != NULL;
3564 }
3565
3566 /*
3567  * mono_aot_handle_pagefault:
3568  *
3569  *   Handle a pagefault caused by an unreadable page by making it readable again.
3570  */
3571 void
3572 mono_aot_handle_pagefault (void *ptr)
3573 {
3574 #ifndef PLATFORM_WIN32
3575         guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
3576         int res;
3577
3578         mono_aot_lock ();
3579         res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
3580         g_assert (res == 0);
3581
3582         n_pagefaults ++;
3583         mono_aot_unlock ();
3584 #endif
3585 }
3586
3587 #else
3588 /* AOT disabled */
3589
3590 void
3591 mono_aot_init (void)
3592 {
3593 }
3594
3595 gpointer
3596 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
3597 {
3598         return NULL;
3599 }
3600
3601 gboolean
3602 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3603 {
3604         return FALSE;
3605 }
3606
3607 gboolean
3608 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
3609 {
3610         return FALSE;
3611 }
3612
3613 gboolean
3614 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
3615 {
3616         return FALSE;
3617 }
3618
3619 MonoJitInfo *
3620 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
3621 {
3622         return NULL;
3623 }
3624
3625 gpointer
3626 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3627 {
3628         return NULL;
3629 }
3630
3631 guint8*
3632 mono_aot_get_plt_entry (guint8 *code)
3633 {
3634         return NULL;
3635 }
3636
3637 gpointer
3638 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3639 {
3640         return NULL;
3641 }
3642
3643 void
3644 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
3645 {
3646 }
3647
3648 gpointer
3649 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
3650 {
3651         return NULL;
3652 }
3653
3654 guint32
3655 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3656 {
3657         g_assert_not_reached ();
3658
3659         return 0;
3660 }
3661
3662 gpointer
3663 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
3664 {
3665         g_assert_not_reached ();
3666         return NULL;
3667 }
3668
3669 gpointer
3670 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
3671 {
3672         g_assert_not_reached ();
3673         return NULL;
3674 }
3675
3676 gpointer
3677 mono_aot_get_trampoline (const char *name)
3678 {
3679         g_assert_not_reached ();
3680         return NULL;
3681 }
3682
3683 gpointer
3684 mono_aot_get_unbox_trampoline (MonoMethod *method)
3685 {
3686         g_assert_not_reached ();
3687         return NULL;
3688 }
3689
3690 gpointer
3691 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
3692 {
3693         g_assert_not_reached ();
3694         return NULL;
3695 }
3696
3697 gpointer
3698 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
3699 {
3700         g_assert_not_reached ();
3701         return NULL;
3702 }       
3703
3704 guint8*
3705 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
3706 {
3707         g_assert_not_reached ();
3708         return NULL;
3709 }
3710
3711 void
3712 mono_aot_register_jit_icall (const char *name, gpointer addr)
3713 {
3714 }
3715
3716 #endif