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