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