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