2010-06-29 Zoltan Varga <vargaz@gmail.com>
[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
967         if (mono_compile_aot)
968                 return;
969
970         if (assembly->image->aot_module)
971                 /* 
972                  * Already loaded. This can happen because the assembly loading code might invoke
973                  * the assembly load hooks multiple times for the same assembly.
974                  */
975                 return;
976
977         if (assembly->image->dynamic)
978                 return;
979
980         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
981                 return;
982
983         mono_aot_lock ();
984         if (static_aot_modules)
985                 globals = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
986         else
987                 globals = NULL;
988         mono_aot_unlock ();
989
990         if (globals) {
991                 /* Statically linked AOT module */
992                 sofile = NULL;
993                 aot_name = g_strdup_printf ("%s", assembly->aname.name);
994                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
995         } else {
996                 if (use_aot_cache)
997                         sofile = load_aot_module_from_cache (assembly, &aot_name);
998                 else {
999                         char *err;
1000                         aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
1001
1002                         sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
1003
1004                         if (!sofile) {
1005                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err);
1006                                 g_free (err);
1007                         }
1008                 }
1009         }
1010
1011         if (!sofile && !globals) {
1012                 if (mono_aot_only) {
1013                         fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
1014                         exit (1);
1015                 }
1016                 g_free (aot_name);
1017                 return;
1018         }
1019
1020         find_symbol (sofile, globals, "mono_assembly_guid", (gpointer *) &saved_guid);
1021         find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &aot_version);
1022         find_symbol (sofile, globals, "mono_aot_opt_flags", (gpointer *)&opt_flags);
1023         find_symbol (sofile, globals, "mono_runtime_version", (gpointer *)&runtime_version);
1024         find_symbol (sofile, globals, "mono_aot_got_addr", (gpointer *)&got_addr);
1025
1026         if (!aot_version || strcmp (aot_version, MONO_AOT_FILE_VERSION)) {
1027                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s has wrong file format version (expected %s got %s)\n", aot_name, MONO_AOT_FILE_VERSION, aot_version);
1028                 usable = FALSE;
1029         }
1030         else {
1031                 if (!saved_guid || strcmp (assembly->image->guid, saved_guid)) {
1032                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date.\n", aot_name);
1033                         usable = FALSE;
1034                 }
1035         }
1036
1037         build_info = mono_get_runtime_build_info ();
1038         if (!runtime_version || ((strlen (runtime_version) > 0 && strcmp (runtime_version, build_info)))) {
1039                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled against runtime version '%s' while this runtime has version '%s'.\n", aot_name, runtime_version, build_info);
1040                 usable = FALSE;
1041         }
1042         g_free (build_info);
1043
1044         find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&file_info);
1045         g_assert (file_info);
1046
1047         full_aot = ((MonoAotFileInfo*)file_info)->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1048
1049         if (mono_aot_only && !full_aot) {
1050                 fprintf (stderr, "Can't use AOT image '%s' in aot-only mode because it is not compiled with --aot=full.\n", aot_name);
1051                 exit (1);
1052         }
1053         if (!mono_aot_only && full_aot) {
1054                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled with --aot=full.\n", aot_name);
1055                 usable = FALSE;
1056         }
1057
1058         if ((((MonoAotFileInfo*)file_info)->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) {
1059                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled with LLVM.\n", aot_name);
1060                 usable = FALSE;
1061         }
1062
1063         if (!usable) {
1064                 if (mono_aot_only) {
1065                         fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode.\n", aot_name);
1066                         exit (1);
1067                 }
1068                 g_free (aot_name);
1069                 if (sofile)
1070                         mono_dl_close (sofile);
1071                 assembly->image->aot_module = NULL;
1072                 return;
1073         }
1074
1075         amodule = g_new0 (MonoAotModule, 1);
1076         amodule->aot_name = aot_name;
1077         amodule->assembly = assembly;
1078
1079         memcpy (&amodule->info, file_info, sizeof (*file_info));
1080
1081         amodule->got = *got_addr;
1082         amodule->got [0] = assembly->image;
1083         amodule->globals = globals;
1084         amodule->sofile = sofile;
1085         amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
1086
1087         /* Read image table */
1088         {
1089                 guint32 table_len, i;
1090                 char *table = NULL;
1091
1092                 find_symbol (sofile, globals, "mono_image_table", (gpointer *)&table);
1093                 g_assert (table);
1094
1095                 table_len = *(guint32*)table;
1096                 table += sizeof (guint32);
1097                 amodule->image_table = g_new0 (MonoImage*, table_len);
1098                 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
1099                 amodule->image_guids = g_new0 (char*, table_len);
1100                 amodule->image_table_len = table_len;
1101                 for (i = 0; i < table_len; ++i) {
1102                         MonoAssemblyName *aname = &(amodule->image_names [i]);
1103
1104                         aname->name = g_strdup (table);
1105                         table += strlen (table) + 1;
1106                         amodule->image_guids [i] = g_strdup (table);
1107                         table += strlen (table) + 1;
1108                         if (table [0] != 0)
1109                                 aname->culture = g_strdup (table);
1110                         table += strlen (table) + 1;
1111                         memcpy (aname->public_key_token, table, strlen (table) + 1);
1112                         table += strlen (table) + 1;                    
1113
1114                         table = ALIGN_PTR_TO (table, 8);
1115                         aname->flags = *(guint32*)table;
1116                         table += 4;
1117                         aname->major = *(guint32*)table;
1118                         table += 4;
1119                         aname->minor = *(guint32*)table;
1120                         table += 4;
1121                         aname->build = *(guint32*)table;
1122                         table += 4;
1123                         aname->revision = *(guint32*)table;
1124                         table += 4;
1125                 }
1126         }
1127
1128         /* Read method and method_info tables */
1129         find_symbol (sofile, globals, "code_offsets", (gpointer*)&amodule->code_offsets);
1130         find_symbol (sofile, globals, "methods", (gpointer*)&amodule->code);
1131         find_symbol (sofile, globals, "methods_end", (gpointer*)&amodule->code_end);
1132         find_symbol (sofile, globals, "method_info_offsets", (gpointer*)&amodule->method_info_offsets);
1133         find_symbol (sofile, globals, "ex_info_offsets", (gpointer*)&amodule->ex_info_offsets);
1134         find_symbol (sofile, globals, "blob", (gpointer*)&amodule->blob);
1135         find_symbol (sofile, globals, "class_info_offsets", (gpointer*)&amodule->class_info_offsets);
1136         find_symbol (sofile, globals, "class_name_table", (gpointer *)&amodule->class_name_table);
1137         find_symbol (sofile, globals, "extra_method_table", (gpointer *)&amodule->extra_method_table);
1138         find_symbol (sofile, globals, "extra_method_info_offsets", (gpointer *)&amodule->extra_method_info_offsets);
1139         find_symbol (sofile, globals, "got_info_offsets", (gpointer*)&amodule->got_info_offsets);
1140         find_symbol (sofile, globals, "specific_trampolines", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC]));
1141         find_symbol (sofile, globals, "static_rgctx_trampolines", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX]));
1142         find_symbol (sofile, globals, "imt_thunks", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK]));
1143         find_symbol (sofile, globals, "unwind_info", (gpointer)&amodule->unwind_info);
1144         find_symbol (sofile, globals, "mem_end", (gpointer*)&amodule->mem_end);
1145
1146         amodule->mem_begin = amodule->code;
1147
1148         find_symbol (sofile, globals, "plt", (gpointer*)&amodule->plt);
1149         find_symbol (sofile, globals, "plt_end", (gpointer*)&amodule->plt_end);
1150
1151         if (make_unreadable) {
1152 #ifndef TARGET_WIN32
1153                 guint8 *addr;
1154                 guint8 *page_start, *page_end;
1155                 int err, len;
1156
1157                 addr = amodule->mem_begin;
1158                 len = amodule->mem_end - amodule->mem_begin;
1159
1160                 /* Round down in both directions to avoid modifying data which is not ours */
1161                 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
1162                 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
1163                 if (page_end > page_start) {
1164                         err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
1165                         g_assert (err == 0);
1166                 }
1167 #endif
1168         }
1169
1170         mono_aot_lock ();
1171
1172         aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
1173         aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);
1174
1175         g_hash_table_insert (aot_modules, assembly, amodule);
1176         mono_aot_unlock ();
1177
1178         mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);
1179
1180         assembly->image->aot_module = amodule;
1181  
1182 #if defined(HAVE_DL_ITERATE_PHDR) && defined(PT_GNU_EH_FRAME)
1183         /* Lookup the address of the .eh_frame_hdr () section if available */
1184         dl_iterate_phdr (dl_callback, amodule);
1185 #endif  
1186
1187         if (mono_aot_only) {
1188                 if (mono_defaults.corlib) {
1189                         /* The second got slot contains the mscorlib got addr */
1190                         MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1191
1192                         amodule->got [1] = mscorlib_amodule->got;
1193                 } else {
1194                         amodule->got [1] = amodule->got;
1195                 }
1196         }
1197
1198         /*
1199          * Since we store methoddef and classdef tokens when referring to methods/classes in
1200          * referenced assemblies, we depend on the exact versions of the referenced assemblies.
1201          * MS calls this 'hard binding'. This means we have to load all referenced assemblies
1202          * non-lazily, since we can't handle out-of-date errors later.
1203          * The cached class info also depends on the exact assemblies.
1204          */
1205         for (i = 0; i < amodule->image_table_len; ++i)
1206                 load_image (amodule, i, FALSE);
1207
1208         if (amodule->out_of_date) {
1209                 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);
1210                 if (mono_aot_only) {
1211                         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);
1212                         exit (1);
1213                 }
1214         }
1215         else
1216                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
1217 }
1218
1219 /*
1220  * mono_aot_register_globals:
1221  *
1222  *   This is called by the ctor function in AOT images compiled with the
1223  * 'no-dlsym' option.
1224  */
1225 void
1226 mono_aot_register_globals (gpointer *globals)
1227 {
1228         g_assert_not_reached ();
1229 }
1230
1231 /*
1232  * mono_aot_register_module:
1233  *
1234  *   This should be called by embedding code to register AOT modules statically linked
1235  * into the executable. AOT_INFO should be the value of the 
1236  * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
1237  */
1238 void
1239 mono_aot_register_module (gpointer *aot_info)
1240 {
1241         gpointer *globals;
1242         char *aname;
1243
1244         globals = aot_info;
1245         g_assert (globals);
1246
1247         /* Determine the assembly name */
1248         find_symbol (NULL, globals, "mono_aot_assembly_name", (gpointer*)&aname);
1249         g_assert (aname);
1250
1251         /* This could be called before startup */
1252         if (aot_modules)
1253                 mono_aot_lock ();
1254
1255         if (!static_aot_modules)
1256                 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
1257
1258         g_hash_table_insert (static_aot_modules, aname, globals);
1259
1260         if (aot_modules)
1261                 mono_aot_unlock ();
1262 }
1263
1264 void
1265 mono_aot_init (void)
1266 {
1267         InitializeCriticalSection (&aot_mutex);
1268         aot_modules = g_hash_table_new (NULL, NULL);
1269
1270         mono_install_assembly_load_hook (load_aot_module, NULL);
1271
1272         if (g_getenv ("MONO_LASTAOT"))
1273                 mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
1274         if (g_getenv ("MONO_AOT_CACHE"))
1275                 use_aot_cache = TRUE;
1276 }
1277
1278 static gboolean
1279 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
1280 {
1281         guint32 flags;
1282
1283         info->vtable_size = decode_value (buf, &buf);
1284         if (info->vtable_size == -1)
1285                 /* Generic type */
1286                 return FALSE;
1287         flags = decode_value (buf, &buf);
1288         info->ghcimpl = (flags >> 0) & 0x1;
1289         info->has_finalize = (flags >> 1) & 0x1;
1290         info->has_cctor = (flags >> 2) & 0x1;
1291         info->has_nested_classes = (flags >> 3) & 0x1;
1292         info->blittable = (flags >> 4) & 0x1;
1293         info->has_references = (flags >> 5) & 0x1;
1294         info->has_static_refs = (flags >> 6) & 0x1;
1295         info->no_special_static_fields = (flags >> 7) & 0x1;
1296         info->is_generic_container = (flags >> 8) & 0x1;
1297
1298         if (info->has_cctor) {
1299                 MonoImage *cctor_image = decode_method_ref (module, &info->cctor_token, NULL, NULL, buf, &buf);
1300                 if (!cctor_image)
1301                         return FALSE;
1302         }
1303         if (info->has_finalize) {
1304                 info->finalize_image = decode_method_ref (module, &info->finalize_token, NULL, NULL, buf, &buf);
1305                 if (!info->finalize_image)
1306                         return FALSE;
1307         }
1308
1309         info->instance_size = decode_value (buf, &buf);
1310         info->class_size = decode_value (buf, &buf);
1311         info->packing_size = decode_value (buf, &buf);
1312         info->min_align = decode_value (buf, &buf);
1313
1314         *endbuf = buf;
1315
1316         return TRUE;
1317 }       
1318
1319 gpointer
1320 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
1321 {
1322         int i;
1323         MonoClass *klass = vtable->klass;
1324         MonoAotModule *aot_module = klass->image->aot_module;
1325         guint8 *info, *p;
1326         MonoCachedClassInfo class_info;
1327         gboolean err;
1328         guint32 token;
1329         MonoImage *image;
1330         gboolean no_aot_trampoline;
1331
1332         if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !aot_module)
1333                 return NULL;
1334
1335         info = &aot_module->blob [mono_aot_get_offset (aot_module->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1336         p = info;
1337
1338         err = decode_cached_class_info (aot_module, &class_info, p, &p);
1339         if (!err)
1340                 return NULL;
1341
1342         for (i = 0; i < slot; ++i)
1343                 decode_method_ref (aot_module, &token, NULL, NULL, p, &p);
1344
1345         image = decode_method_ref (aot_module, &token, NULL, &no_aot_trampoline, p, &p);
1346         if (!image)
1347                 return NULL;
1348         if (no_aot_trampoline)
1349                 return NULL;
1350
1351         if (mono_metadata_token_index (token) == 0)
1352                 return NULL;
1353
1354         return mono_aot_get_method_from_token (domain, image, token);
1355 }
1356
1357 gboolean
1358 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
1359 {
1360         MonoAotModule *aot_module = klass->image->aot_module;
1361         guint8 *p;
1362         gboolean err;
1363
1364         if (klass->rank || !aot_module)
1365                 return FALSE;
1366
1367         p = (guint8*)&aot_module->blob [mono_aot_get_offset (aot_module->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1368
1369         err = decode_cached_class_info (aot_module, res, p, &p);
1370         if (!err)
1371                 return FALSE;
1372
1373         return TRUE;
1374 }
1375
1376 /**
1377  * mono_aot_get_class_from_name:
1378  *
1379  *  Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
1380  * using a cache stored in the AOT file.
1381  * Stores the resulting class in *KLASS if found, stores NULL otherwise.
1382  *
1383  * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was 
1384  * found.
1385  */
1386 gboolean
1387 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
1388 {
1389         MonoAotModule *aot_module = image->aot_module;
1390         guint16 *table, *entry;
1391         guint16 table_size;
1392         guint32 hash;
1393         char full_name_buf [1024];
1394         char *full_name;
1395         const char *name2, *name_space2;
1396         MonoTableInfo  *t;
1397         guint32 cols [MONO_TYPEDEF_SIZE];
1398         GHashTable *nspace_table;
1399
1400         if (!aot_module || !aot_module->class_name_table)
1401                 return FALSE;
1402
1403         mono_aot_lock ();
1404
1405         *klass = NULL;
1406
1407         /* First look in the cache */
1408         if (!aot_module->name_cache)
1409                 aot_module->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
1410         nspace_table = g_hash_table_lookup (aot_module->name_cache, name_space);
1411         if (nspace_table) {
1412                 *klass = g_hash_table_lookup (nspace_table, name);
1413                 if (*klass) {
1414                         mono_aot_unlock ();
1415                         return TRUE;
1416                 }
1417         }
1418
1419         table_size = aot_module->class_name_table [0];
1420         table = aot_module->class_name_table + 1;
1421
1422         if (name_space [0] == '\0')
1423                 full_name = g_strdup_printf ("%s", name);
1424         else {
1425                 if (strlen (name_space) + strlen (name) < 1000) {
1426                         sprintf (full_name_buf, "%s.%s", name_space, name);
1427                         full_name = full_name_buf;
1428                 } else {
1429                         full_name = g_strdup_printf ("%s.%s", name_space, name);
1430                 }
1431         }
1432         hash = mono_metadata_str_hash (full_name) % table_size;
1433         if (full_name != full_name_buf)
1434                 g_free (full_name);
1435
1436         entry = &table [hash * 2];
1437
1438         if (entry [0] != 0) {
1439                 t = &image->tables [MONO_TABLE_TYPEDEF];
1440
1441                 while (TRUE) {
1442                         guint32 index = entry [0];
1443                         guint32 next = entry [1];
1444                         guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
1445
1446                         name_table_accesses ++;
1447
1448                         mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
1449
1450                         name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1451                         name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1452
1453                         if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
1454                                 mono_aot_unlock ();
1455                                 *klass = mono_class_get (image, token);
1456
1457                                 /* Add to cache */
1458                                 if (*klass) {
1459                                         mono_aot_lock ();
1460                                         nspace_table = g_hash_table_lookup (aot_module->name_cache, name_space);
1461                                         if (!nspace_table) {
1462                                                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
1463                                                 g_hash_table_insert (aot_module->name_cache, (char*)name_space2, nspace_table);
1464                                         }
1465                                         g_hash_table_insert (nspace_table, (char*)name2, *klass);
1466                                         mono_aot_unlock ();
1467                                 }
1468                                 return TRUE;
1469                         }
1470
1471                         if (next != 0) {
1472                                 entry = &table [next * 2];
1473                         } else {
1474                                 break;
1475                         }
1476                 }
1477         }
1478
1479         mono_aot_unlock ();
1480         
1481         return TRUE;
1482 }
1483
1484 #define DW_EH_PE_omit   0xff
1485 #define DW_EH_PE_uleb128 0x01
1486 #define DW_EH_PE_udata2 0x02
1487 #define DW_EH_PE_udata4 0x03
1488 #define DW_EH_PE_udata8 0x04
1489 #define DW_EH_PE_sleb128 0x09
1490 #define DW_EH_PE_sdata2 0x0A
1491 #define DW_EH_PE_sdata4 0x0B
1492 #define DW_EH_PE_sdata8 0x0C
1493
1494 #define DW_EH_PE_absptr 0x00
1495 #define DW_EH_PE_pcrel  0x10
1496 #define DW_EH_PE_datarel 0x30
1497 #define DW_EH_PE_omit   0xff
1498
1499 typedef struct
1500 {
1501         guint8 version;
1502         guint8 eh_frame_ptr_enc;
1503         guint8 fde_count_enc;
1504         guint8 table_enc;
1505         guint8 rest;
1506 } eh_frame_hdr;
1507
1508 /*
1509  * decode_eh_frame:
1510  *
1511  *   Decode the exception handling information in the .eh_frame section of the AOT
1512  * file belong to CODE, and construct a MonoJitInfo structure from it.
1513  * LOCKING: Acquires the domain lock.
1514  */
1515 static G_GNUC_UNUSED MonoJitInfo*
1516 decode_eh_frame (MonoAotModule *amodule, MonoDomain *domain, 
1517                                  MonoMethod *method, guint8 *code, 
1518                                  MonoJitExceptionInfo *clauses, int num_clauses,
1519                                  int extra_size, GSList **nesting,
1520                                  int *this_reg, int *this_offset)
1521 {
1522         eh_frame_hdr *hdr;
1523         guint8 *p;
1524         guint8 *eh_frame, *unwind_info;
1525         guint32 eh_frame_ptr;
1526         int fde_count;
1527         gint32 *table;
1528         int i, j, pos, left, right, offset, offset1, offset2;
1529         guint32 unw_len, code_len;
1530         MonoJitExceptionInfo *ei;
1531         guint32 ei_len, nested_len, nindex;
1532         gpointer *type_info;
1533         MonoJitInfo *jinfo;
1534
1535         g_assert (amodule->eh_frame_hdr);
1536
1537         // http://refspecs.freestandards.org/LSB_1.3.0/gLSB/gLSB/ehframehdr.html
1538         hdr = (eh_frame_hdr*)amodule->eh_frame_hdr;
1539         g_assert (hdr->version == 1);
1540         g_assert (hdr->eh_frame_ptr_enc == (DW_EH_PE_pcrel | DW_EH_PE_sdata4));
1541         g_assert (hdr->fde_count_enc == DW_EH_PE_udata4);
1542         g_assert (hdr->table_enc == (DW_EH_PE_datarel | DW_EH_PE_sdata4));
1543
1544         p = &(hdr->rest);
1545         eh_frame_ptr = *(guint32*)p;
1546         p += 4;
1547         fde_count = *(guint32*)p;
1548         p += 4;
1549         table = (gint32*)p;
1550
1551         /* Binary search in the table to find the entry for code */
1552         offset = code - amodule->eh_frame_hdr;
1553
1554         left = 0;
1555         right = fde_count;
1556         while (TRUE) {
1557                 pos = (left + right) / 2;
1558
1559                 offset1 = table [(pos * 2)];
1560                 if (pos + 1 == fde_count)
1561                         /* FIXME: */
1562                         offset2 = amodule->code_end - amodule->code;
1563                 else
1564                         offset2 = table [(pos + 1) * 2];
1565
1566                 if (offset < offset1)
1567                         right = pos;
1568                 else if (offset >= offset2)
1569                         left = pos + 1;
1570                 else
1571                         break;
1572         }
1573
1574         g_assert (code >= amodule->eh_frame_hdr + table [(pos * 2)]);
1575         if (pos + 1 < fde_count)
1576                 g_assert (code < amodule->eh_frame_hdr + table [(pos * 2) + 2]);
1577
1578         eh_frame = amodule->eh_frame_hdr + table [(pos * 2) + 1];
1579
1580         unwind_info = mono_unwind_decode_fde (eh_frame, &unw_len, &code_len, &ei, &ei_len, &type_info, this_reg, this_offset);
1581
1582         /* Count number of nested clauses */
1583         nested_len = 0;
1584         for (i = 0; i < ei_len; ++i) {
1585                 gint32 cindex1 = *(gint32*)type_info [i];
1586                 GSList *l;
1587
1588                 for (l = nesting [cindex1]; l; l = l->next) {
1589                         gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
1590
1591                         for (j = 0; j < ei_len; ++j) {
1592                                 gint32 cindex2 = *(gint32*)type_info [j];
1593
1594                                 if (cindex2 == nesting_cindex)
1595                                         nested_len ++;
1596                         }
1597                 }
1598         }
1599
1600         /*
1601          * LLVM might represent one IL region with multiple regions, so have to
1602          * allocate a new JI.
1603          */
1604         jinfo = 
1605                 mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * (ei_len + nested_len)) + extra_size);
1606
1607         jinfo->code_size = code_len;
1608         jinfo->used_regs = mono_cache_unwind_info (unwind_info, unw_len);
1609         jinfo->method = method;
1610         jinfo->code_start = code;
1611         jinfo->domain_neutral = 0;
1612         /* This signals that used_regs points to a normal cached unwind info */
1613         jinfo->from_aot = 0;
1614         jinfo->num_clauses = ei_len + nested_len;
1615
1616         for (i = 0; i < ei_len; ++i) {
1617                 /*
1618                  * orig_jinfo contains the original IL exception info saved by the AOT
1619                  * compiler, we have to combine that with the information produced by LLVM
1620                  */
1621                 /* The type_info entries contain IL clause indexes */
1622                 int clause_index = *(gint32*)type_info [i];
1623                 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
1624                 MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
1625
1626                 g_assert (clause_index < num_clauses);
1627                 jei->flags = orig_jei->flags;
1628                 jei->data.catch_class = orig_jei->data.catch_class;
1629
1630                 jei->try_start = ei [i].try_start;
1631                 jei->try_end = ei [i].try_end;
1632                 jei->handler_start = ei [i].handler_start;
1633         }
1634
1635         /* See exception_cb () in mini-llvm.c as to why this is needed */
1636         nindex = ei_len;
1637         for (i = 0; i < ei_len; ++i) {
1638                 gint32 cindex1 = *(gint32*)type_info [i];
1639                 GSList *l;
1640
1641                 for (l = nesting [cindex1]; l; l = l->next) {
1642                         gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
1643
1644                         for (j = 0; j < ei_len; ++j) {
1645                                 gint32 cindex2 = *(gint32*)type_info [j];
1646
1647                                 if (cindex2 == nesting_cindex) {
1648                                         /* 
1649                                          * The try interval comes from the nested clause, everything else from the
1650                                          * nesting clause.
1651                                          */
1652                                         memcpy (&jinfo->clauses [nindex], &jinfo->clauses [j], sizeof (MonoJitExceptionInfo));
1653                                         jinfo->clauses [nindex].try_start = jinfo->clauses [i].try_start;
1654                                         jinfo->clauses [nindex].try_end = jinfo->clauses [i].try_end;
1655                                         nindex ++;
1656                                 }
1657                         }
1658                 }
1659         }
1660         g_assert (nindex == ei_len + nested_len);
1661
1662         return jinfo;
1663 }
1664
1665 /*
1666  * LOCKING: Acquires the domain lock.
1667  */
1668 static MonoJitInfo*
1669 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain, 
1670                                                          MonoMethod *method, guint8* ex_info, guint8 *addr,
1671                                                          guint8 *code, guint32 code_len)
1672 {
1673         int i, buf_len, num_clauses;
1674         MonoJitInfo *jinfo;
1675         guint used_int_regs, flags;
1676         gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes;
1677         gboolean from_llvm;
1678         guint8 *p;
1679         int generic_info_size, try_holes_info_size, num_holes, this_reg, this_offset;
1680
1681         /* Load the method info from the AOT file */
1682
1683         p = ex_info;
1684         flags = decode_value (p, &p);
1685         has_generic_jit_info = (flags & 1) != 0;
1686         has_dwarf_unwind_info = (flags & 2) != 0;
1687         has_clauses = (flags & 4) != 0;
1688         has_seq_points = (flags & 8) != 0;
1689         from_llvm = (flags & 16) != 0;
1690         has_try_block_holes = (flags & 32) != 0;
1691
1692         if (has_dwarf_unwind_info) {
1693                 guint32 offset;
1694
1695                 offset = decode_value (p, &p);
1696                 g_assert (offset < (1 << 30));
1697                 used_int_regs = offset;
1698         } else {
1699                 used_int_regs = decode_value (p, &p);
1700         }
1701         if (has_generic_jit_info)
1702                 generic_info_size = sizeof (MonoGenericJitInfo);
1703         else
1704                 generic_info_size = 0;
1705
1706         if (has_try_block_holes) {
1707                 num_holes = decode_value (p, &p);
1708                 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
1709         } else {
1710                 num_holes = try_holes_info_size = 0;
1711         }
1712         /* Exception table */
1713         if (has_clauses)
1714                 num_clauses = decode_value (p, &p);
1715         else
1716                 num_clauses = 0;
1717
1718         if (from_llvm) {
1719                 MonoJitExceptionInfo *clauses;
1720                 GSList **nesting;
1721
1722                 /*
1723                  * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
1724                  * section.
1725                  */
1726                 clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
1727                 nesting = g_new0 (GSList*, num_clauses);
1728
1729                 for (i = 0; i < num_clauses; ++i) {
1730                         MonoJitExceptionInfo *ei = &clauses [i];
1731
1732                         ei->flags = decode_value (p, &p);
1733
1734                         if (decode_value (p, &p))
1735                                 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
1736
1737                         /* Read the list of nesting clauses */
1738                         while (TRUE) {
1739                                 int nesting_index = decode_value (p, &p);
1740                                 if (nesting_index == -1)
1741                                         break;
1742                                 nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
1743                         }
1744                 }
1745
1746                 jinfo = decode_eh_frame (amodule, domain, method, code, clauses, num_clauses, generic_info_size + try_holes_info_size, nesting, &this_reg, &this_offset);
1747                 jinfo->from_llvm = 1;
1748
1749                 g_free (clauses);
1750                 for (i = 0; i < num_clauses; ++i)
1751                         g_slist_free (nesting [i]);
1752                 g_free (nesting);
1753         } else {
1754                 jinfo = 
1755                         mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size);
1756                 jinfo->num_clauses = num_clauses;
1757
1758                 for (i = 0; i < jinfo->num_clauses; ++i) {
1759                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
1760
1761                         ei->flags = decode_value (p, &p);
1762
1763                         ei->exvar_offset = decode_value (p, &p);
1764
1765                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
1766                                 ei->data.filter = code + decode_value (p, &p);
1767                         else {
1768                                 if (decode_value (p, &p))
1769                                         ei->data.catch_class = decode_klass_ref (amodule, p, &p);
1770                         }
1771
1772                         ei->try_start = code + decode_value (p, &p);
1773                         ei->try_end = code + decode_value (p, &p);
1774                         ei->handler_start = code + decode_value (p, &p);
1775                 }
1776
1777                 jinfo->code_size = code_len;
1778                 jinfo->used_regs = used_int_regs;
1779                 jinfo->method = method;
1780                 jinfo->code_start = code;
1781                 jinfo->domain_neutral = 0;
1782                 jinfo->from_aot = 1;
1783         }
1784
1785         if (has_generic_jit_info) {
1786                 MonoGenericJitInfo *gi;
1787
1788                 jinfo->has_generic_jit_info = 1;
1789
1790                 gi = mono_jit_info_get_generic_jit_info (jinfo);
1791                 g_assert (gi);
1792
1793                 if (from_llvm) {
1794                         gi->has_this = this_reg != -1;
1795                         gi->this_reg = this_reg;
1796                         gi->this_offset = this_offset;
1797                 } else {
1798                         gi->has_this = decode_value (p, &p);
1799                         gi->this_reg = decode_value (p, &p);
1800                         gi->this_offset = decode_value (p, &p);
1801                 }
1802
1803                 /* This currently contains no data */
1804                 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
1805
1806                 jinfo->method = decode_resolve_method_ref (amodule, p, &p);
1807         }
1808
1809         if (has_try_block_holes) {
1810                 MonoTryBlockHoleTableJitInfo *table;
1811
1812                 jinfo->has_try_block_holes = 1;
1813
1814                 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
1815                 g_assert (table);
1816
1817                 table->num_holes = (guint16)num_holes;
1818                 for (i = 0; i < num_holes; ++i) {
1819                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
1820                         hole->clause = decode_value (p, &p);
1821                         hole->length = decode_value (p, &p);
1822                         hole->offset = decode_value (p, &p);
1823                 }
1824         }
1825
1826         if (has_seq_points) {
1827                 MonoSeqPointInfo *seq_points;
1828                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
1829
1830                 int len = decode_value (p, &p);
1831
1832                 seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
1833                 seq_points->len = len;
1834                 last_il_offset = last_native_offset = 0;
1835                 for (i = 0; i < len; ++i) {
1836                         SeqPoint *sp = &seq_points->seq_points [i];
1837                         il_offset = last_il_offset + decode_value (p, &p);
1838                         native_offset = last_native_offset + decode_value (p, &p);
1839
1840                         sp->il_offset = il_offset;
1841                         sp->native_offset = native_offset;
1842                         
1843                         sp->next_len = decode_value (p, &p);
1844                         sp->next = g_new (int, sp->next_len);
1845                         for (j = 0; j < sp->next_len; ++j)
1846                                 sp->next [j] = decode_value (p, &p);
1847
1848                         last_il_offset = il_offset;
1849                         last_native_offset = native_offset;
1850                 }
1851
1852                 mono_domain_lock (domain);
1853                 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
1854                 mono_domain_unlock (domain);
1855         }
1856
1857         /* Load debug info */
1858         buf_len = decode_value (p, &p);
1859         mono_debug_add_aot_method (domain, method, code, p, buf_len);
1860
1861         if (amodule != jinfo->method->klass->image->aot_module) {
1862                 mono_aot_lock ();
1863                 if (!ji_to_amodule)
1864                         ji_to_amodule = g_hash_table_new (NULL, NULL);
1865                 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
1866                 mono_aot_unlock ();             
1867         }
1868         
1869         return jinfo;
1870 }
1871
1872 /*
1873  * mono_aot_get_unwind_info:
1874  *
1875  *   Return a pointer to the DWARF unwind info belonging to JI.
1876  */
1877 guint8*
1878 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
1879 {
1880         MonoAotModule *amodule = ji->method->klass->image->aot_module;
1881         guint8 *p;
1882         guint8 *code = ji->code_start;
1883
1884         g_assert (amodule);
1885         g_assert (ji->from_aot);
1886
1887         if (!(code >= amodule->code && code <= amodule->code_end)) {
1888                 /* ji belongs to a different aot module than amodule */
1889                 mono_aot_lock ();
1890                 g_assert (ji_to_amodule);
1891                 amodule = g_hash_table_lookup (ji_to_amodule, ji);
1892                 g_assert (amodule);
1893                 g_assert (code >= amodule->code && code <= amodule->code_end);
1894                 mono_aot_unlock ();
1895         }
1896
1897         p = amodule->unwind_info + ji->used_regs;
1898         *unwind_info_len = decode_value (p, &p);
1899         return p;
1900 }
1901
1902 static G_GNUC_UNUSED int
1903 compare_ints (const void *a, const void *b)
1904 {
1905         return *(gint32*)a - *(gint32*)b;
1906 }
1907
1908 static void
1909 msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch)
1910 {
1911         int mid = (lo + hi) / 2;
1912         int i, t_lo, t_hi;
1913
1914         if (lo >= hi)
1915                 return;
1916
1917         if (hi - lo < 32) {
1918                 for (i = lo; i < hi; ++i)
1919                         if (array [(i * 2)] > array [(i * 2) + 2])
1920                                 break;
1921                 if (i == hi)
1922                         /* Already sorted */
1923                         return;
1924         }
1925
1926         msort_code_offsets_internal (array, lo, mid, scratch);
1927         msort_code_offsets_internal (array, mid + 1, hi, scratch);
1928
1929         if (array [mid * 2] < array [(mid + 1) * 2])
1930                 return;
1931
1932         /* Merge */
1933         t_lo = lo;
1934         t_hi = mid + 1;
1935         for (i = lo; i <= hi; i ++) {
1936                 if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) {
1937                         scratch [(i * 2)] = array [t_lo * 2];
1938                         scratch [(i * 2) + 1] = array [(t_lo *2) + 1];
1939                         t_lo ++;
1940                 } else {
1941                         scratch [(i * 2)] = array [t_hi * 2];
1942                         scratch [(i * 2) + 1] = array [(t_hi *2) + 1];
1943                         t_hi ++;
1944                 }
1945         }
1946         for (i = lo; i <= hi; ++i) {
1947                 array [(i * 2)] = scratch [i * 2];
1948                 array [(i * 2) + 1] = scratch [(i * 2) + 1];
1949         }
1950 }
1951
1952 static void
1953 msort_code_offsets (gint32 *array, int len)
1954 {
1955         gint32 *scratch;
1956
1957         scratch = g_new (gint32, len * 2);
1958         msort_code_offsets_internal (array, 0, len - 1, scratch);
1959         g_free (scratch);
1960 }
1961
1962 MonoJitInfo *
1963 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
1964 {
1965         int pos, left, right, offset, offset1, offset2, code_len;
1966         int method_index, table_len, is_wrapper;
1967         guint32 token;
1968         MonoAotModule *amodule = image->aot_module;
1969         MonoMethod *method;
1970         MonoJitInfo *jinfo;
1971         guint8 *code, *ex_info, *p;
1972         guint32 *table;
1973         int nmethods = amodule->info.nmethods;
1974         gint32 *code_offsets;
1975         int offsets_len, i;
1976
1977         if (!amodule)
1978                 return NULL;
1979
1980         if (domain != mono_get_root_domain ())
1981                 /* FIXME: */
1982                 return NULL;
1983
1984         offset = (guint8*)addr - amodule->code;
1985
1986         /* Compute a sorted table mapping code offsets to method indexes. */
1987         if (!amodule->sorted_code_offsets) {
1988
1989                 code_offsets = g_new0 (gint32, nmethods * 2);
1990                 offsets_len = 0;
1991                 for (i = 0; i < nmethods; ++i) {
1992                         /* Skip the -1 entries to speed up sorting */
1993                         if (amodule->code_offsets [i] == 0xffffffff)
1994                                 continue;
1995                         code_offsets [(offsets_len * 2)] = amodule->code_offsets [i];
1996                         code_offsets [(offsets_len *2) + 1] = i;
1997                         offsets_len ++;
1998                 }
1999                 /* Use a merge sort as this is mostly sorted */
2000                 msort_code_offsets (code_offsets, offsets_len);
2001                 //qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints);
2002                 for (i = 0; i < offsets_len -1; ++i)
2003                         g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);
2004
2005                 if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
2006                         /* Somebody got in before us */
2007                         g_free (code_offsets);
2008                 amodule->sorted_code_offsets_len = offsets_len;
2009         }
2010
2011         code_offsets = amodule->sorted_code_offsets;
2012         offsets_len = amodule->sorted_code_offsets_len;
2013
2014         /* Binary search in the sorted_code_offsets table */
2015         left = 0;
2016         right = offsets_len;
2017         while (TRUE) {
2018                 pos = (left + right) / 2;
2019
2020                 offset1 = code_offsets [(pos * 2)];
2021                 if (pos + 1 == offsets_len)
2022                         offset2 = amodule->code_end - amodule->code;
2023                 else
2024                         offset2 = code_offsets [(pos + 1) * 2];
2025
2026                 if (offset < offset1)
2027                         right = pos;
2028                 else if (offset >= offset2)
2029                         left = pos + 1;
2030                 else
2031                         break;
2032         }
2033
2034         g_assert (offset >= code_offsets [(pos * 2)]);
2035         if (pos + 1 < offsets_len)
2036                 g_assert (offset < code_offsets [((pos + 1) * 2)]);
2037         method_index = code_offsets [(pos * 2) + 1];
2038
2039         code = &amodule->code [amodule->code_offsets [method_index]];
2040         ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
2041
2042         if (pos == offsets_len - 1)
2043                 code_len = amodule->code_end - code;
2044         else
2045                 code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];
2046
2047         g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
2048
2049         /* Might be a wrapper/extra method */
2050         if (amodule->extra_methods) {
2051                 mono_aot_lock ();
2052                 method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
2053                 mono_aot_unlock ();
2054         } else {
2055                 method = NULL;
2056         }
2057
2058         if (!method) {
2059                 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
2060                         /* 
2061                          * This is hit for extra methods which are called directly, so they are
2062                          * not in amodule->extra_methods.
2063                          */
2064                         table_len = amodule->extra_method_info_offsets [0];
2065                         table = amodule->extra_method_info_offsets + 1;
2066                         left = 0;
2067                         right = table_len;
2068                         pos = 0;
2069
2070                         /* Binary search */
2071                         while (TRUE) {
2072                                 pos = ((left + right) / 2);
2073
2074                                 g_assert (pos < table_len);
2075
2076                                 if (table [pos * 2] < method_index)
2077                                         left = pos + 1;
2078                                 else if (table [pos * 2] > method_index)
2079                                         right = pos;
2080                                 else
2081                                         break;
2082                         }
2083
2084                         p = amodule->blob + table [(pos * 2) + 1];
2085                         is_wrapper = decode_value (p, &p);
2086                         g_assert (!is_wrapper);
2087                         method = decode_resolve_method_ref (amodule, p, &p);
2088                         g_assert (method);
2089                 } else {
2090                         token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
2091                         method = mono_get_method (image, token, NULL);
2092                 }
2093         }
2094
2095         /* FIXME: */
2096         g_assert (method);
2097
2098         //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2099         
2100         jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);
2101
2102         g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
2103         g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
2104
2105         /* Add it to the normal JitInfo tables */
2106         mono_jit_info_table_add (domain, jinfo);
2107         
2108         return jinfo;
2109 }
2110
2111 static gboolean
2112 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
2113 {
2114         guint8 *p = buf;
2115         gpointer *table;
2116         MonoImage *image;
2117         int i;
2118
2119         switch (ji->type) {
2120         case MONO_PATCH_INFO_METHOD:
2121         case MONO_PATCH_INFO_METHOD_JUMP:
2122         case MONO_PATCH_INFO_ICALL_ADDR:
2123         case MONO_PATCH_INFO_METHOD_RGCTX: {
2124                 guint32 token;
2125                 MonoMethod *method;
2126                 gboolean no_aot_trampoline;
2127
2128                 image = decode_method_ref (aot_module, &token, &method, &no_aot_trampoline, p, &p);
2129                 if (!image)
2130                         goto cleanup;
2131
2132                 if (!method && !mono_aot_only && !no_aot_trampoline && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (token) == MONO_TABLE_METHOD)) {
2133                         ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (image, token));
2134                         ji->type = MONO_PATCH_INFO_ABS;
2135                 }
2136                 else {
2137                         if (method)
2138                                 ji->data.method = method;
2139                         else
2140                                 ji->data.method = mono_get_method (image, token, NULL);
2141                         g_assert (ji->data.method);
2142                         mono_class_init (ji->data.method->klass);
2143                 }
2144                 break;
2145         }
2146         case MONO_PATCH_INFO_INTERNAL_METHOD:
2147         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2148                 guint32 len = decode_value (p, &p);
2149
2150                 ji->data.name = (char*)p;
2151                 p += len + 1;
2152                 break;
2153         }
2154         case MONO_PATCH_INFO_METHODCONST:
2155                 /* Shared */
2156                 ji->data.method = decode_resolve_method_ref (aot_module, p, &p);
2157                 if (!ji->data.method)
2158                         goto cleanup;
2159                 break;
2160         case MONO_PATCH_INFO_VTABLE:
2161         case MONO_PATCH_INFO_CLASS:
2162         case MONO_PATCH_INFO_IID:
2163         case MONO_PATCH_INFO_ADJUSTED_IID:
2164                 /* Shared */
2165                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2166                 if (!ji->data.klass)
2167                         goto cleanup;
2168                 break;
2169         case MONO_PATCH_INFO_CLASS_INIT:
2170         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2171                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2172                 if (!ji->data.klass)
2173                         goto cleanup;
2174                 break;
2175         case MONO_PATCH_INFO_IMAGE:
2176                 ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE);
2177                 if (!ji->data.image)
2178                         goto cleanup;
2179                 break;
2180         case MONO_PATCH_INFO_FIELD:
2181         case MONO_PATCH_INFO_SFLDA:
2182                 /* Shared */
2183                 ji->data.field = decode_field_info (aot_module, p, &p);
2184                 if (!ji->data.field)
2185                         goto cleanup;
2186                 break;
2187         case MONO_PATCH_INFO_SWITCH:
2188                 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
2189                 ji->data.table->table_size = decode_value (p, &p);
2190                 table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
2191                 ji->data.table->table = (MonoBasicBlock**)table;
2192                 for (i = 0; i < ji->data.table->table_size; i++)
2193                         table [i] = (gpointer)(gssize)decode_value (p, &p);
2194                 break;
2195         case MONO_PATCH_INFO_R4: {
2196                 guint32 val;
2197                 
2198                 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
2199                 val = decode_value (p, &p);
2200                 *(float*)ji->data.target = *(float*)&val;
2201                 break;
2202         }
2203         case MONO_PATCH_INFO_R8: {
2204                 guint32 val [2];
2205                 guint64 v;
2206
2207                 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
2208
2209                 val [0] = decode_value (p, &p);
2210                 val [1] = decode_value (p, &p);
2211                 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
2212                 *(double*)ji->data.target = *(double*)&v;
2213                 break;
2214         }
2215         case MONO_PATCH_INFO_LDSTR:
2216                 image = load_image (aot_module, decode_value (p, &p), TRUE);
2217                 if (!image)
2218                         goto cleanup;
2219                 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
2220                 break;
2221         case MONO_PATCH_INFO_RVA:
2222         case MONO_PATCH_INFO_DECLSEC:
2223         case MONO_PATCH_INFO_LDTOKEN:
2224         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2225                 /* Shared */
2226                 image = load_image (aot_module, decode_value (p, &p), TRUE);
2227                 if (!image)
2228                         goto cleanup;
2229                 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
2230
2231                 ji->data.token->has_context = decode_value (p, &p);
2232                 if (ji->data.token->has_context) {
2233                         gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
2234                         if (!res)
2235                                 goto cleanup;
2236                 }
2237                 break;
2238         case MONO_PATCH_INFO_EXC_NAME:
2239                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2240                 if (!ji->data.klass)
2241                         goto cleanup;
2242                 ji->data.name = ji->data.klass->name;
2243                 break;
2244         case MONO_PATCH_INFO_METHOD_REL:
2245                 ji->data.offset = decode_value (p, &p);
2246                 break;
2247         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2248         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2249         case MONO_PATCH_INFO_MONITOR_ENTER:
2250         case MONO_PATCH_INFO_MONITOR_EXIT:
2251                 break;
2252         case MONO_PATCH_INFO_RGCTX_FETCH: {
2253                 gboolean res;
2254                 MonoJumpInfoRgctxEntry *entry;
2255
2256                 entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
2257                 entry->method = decode_resolve_method_ref (aot_module, p, &p);
2258                 entry->in_mrgctx = decode_value (p, &p);
2259                 entry->info_type = decode_value (p, &p);
2260                 entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
2261                 entry->data->type = decode_value (p, &p);
2262                 
2263                 res = decode_patch (aot_module, mp, entry->data, p, &p);
2264                 if (!res)
2265                         goto cleanup;
2266                 ji->data.rgctx_entry = entry;
2267                 break;
2268         }
2269         case MONO_PATCH_INFO_SEQ_POINT_INFO:
2270                 break;
2271         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
2272                 MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));
2273
2274                 imt_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
2275                 imt_tramp->vt_offset = decode_value (p, &p);
2276                 
2277                 ji->data.imt_tramp = imt_tramp;
2278                 break;
2279         }
2280         default:
2281                 g_warning ("unhandled type %d", ji->type);
2282                 g_assert_not_reached ();
2283         }
2284
2285         *endbuf = p;
2286
2287         return TRUE;
2288
2289  cleanup:
2290         return FALSE;
2291 }
2292
2293 static MonoJumpInfo*
2294 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches, 
2295                                  guint32 **got_slots, 
2296                                  guint8 *buf, guint8 **endbuf)
2297 {
2298         MonoJumpInfo *patches;
2299         int pindex;
2300         guint8 *p;
2301
2302         p = buf;
2303
2304         patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
2305
2306         *got_slots = g_malloc (sizeof (guint32) * n_patches);
2307
2308         for (pindex = 0; pindex < n_patches; ++pindex) {
2309                 MonoJumpInfo *ji = &patches [pindex];
2310                 guint8 *shared_p;
2311                 gboolean res;
2312                 guint32 got_offset;
2313
2314                 got_offset = decode_value (p, &p);
2315
2316                 if (aot_module->got [got_offset]) {
2317                         /* Already loaded */
2318                         //printf ("HIT!\n");
2319                 } else {
2320                         shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);
2321
2322                         ji->type = decode_value (shared_p, &shared_p);
2323
2324                         res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
2325                         if (!res)
2326                                 goto cleanup;
2327                 }
2328
2329                 (*got_slots) [pindex] = got_offset;
2330         }
2331
2332         *endbuf = p;
2333         return patches;
2334
2335  cleanup:
2336         g_free (*got_slots);
2337         *got_slots = NULL;
2338
2339         return NULL;
2340 }
2341
2342 static void
2343 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
2344 {
2345         /*
2346          * Jump addresses cannot be patched by the trampoline code since it
2347          * does not have access to the caller's address. Instead, we collect
2348          * the addresses of the GOT slots pointing to a method, and patch
2349          * them after the method has been compiled.
2350          */
2351         MonoJitDomainInfo *info = domain_jit_info (domain);
2352         GSList *list;
2353                 
2354         mono_domain_lock (domain);
2355         if (!info->jump_target_got_slot_hash)
2356                 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
2357         list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
2358         list = g_slist_prepend (list, got_slot);
2359         g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
2360         mono_domain_unlock (domain);
2361 }
2362
2363 /*
2364  * load_method:
2365  *
2366  *   Load the method identified by METHOD_INDEX from the AOT image. Return a
2367  * pointer to the native code of the method, or NULL if not found.
2368  * METHOD might not be set if the caller only has the image/token info.
2369  */
2370 static gpointer
2371 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
2372 {
2373         MonoClass *klass;
2374         gboolean from_plt = method == NULL;
2375         MonoMemPool *mp;
2376         int i, pindex, n_patches, used_strings;
2377         gboolean keep_patches = TRUE;
2378         guint8 *p;
2379         MonoJitInfo *jinfo = NULL;
2380         guint8 *code, *info;
2381
2382         if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
2383                 return NULL;
2384
2385         if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
2386                 /* Non shared AOT code can't be used in other appdomains */
2387                 return NULL;
2388
2389         if (amodule->out_of_date)
2390                 return NULL;
2391
2392         if (amodule->code_offsets [method_index] == 0xffffffff) {
2393                 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2394                         char *full_name;
2395
2396                         if (!method)
2397                                 method = mono_get_method (image, token, NULL);
2398                         full_name = mono_method_full_name (method, TRUE);
2399                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
2400                         g_free (full_name);
2401                 }
2402                 return NULL;
2403         }
2404
2405         code = &amodule->code [amodule->code_offsets [method_index]];
2406
2407         info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
2408
2409         mono_aot_lock ();
2410         if (!amodule->methods_loaded)
2411                 amodule->methods_loaded = g_new0 (guint32, amodule->info.nmethods + 1);
2412         mono_aot_unlock ();
2413
2414         if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
2415                 return code;
2416
2417         if (mono_last_aot_method != -1) {
2418                 if (mono_jit_stats.methods_aot >= mono_last_aot_method)
2419                                 return NULL;
2420                 else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
2421                         if (!method)
2422                                 method = mono_get_method (image, token, NULL);
2423                         if (method) {
2424                                 char *name = mono_method_full_name (method, TRUE);
2425                                 printf ("LAST AOT METHOD: %s.\n", name);
2426                                 g_free (name);
2427                         } else {
2428                                 printf ("LAST AOT METHOD: %p %d\n", code, method_index);
2429                         }
2430                 }
2431         }
2432
2433         p = info;
2434
2435         if (method) {
2436                 klass = method->klass;
2437                 decode_klass_ref (amodule, p, &p);
2438         } else {
2439                 klass = decode_klass_ref (amodule, p, &p);
2440         }
2441
2442         if (amodule->info.opts & MONO_OPT_SHARED)
2443                 used_strings = decode_value (p, &p);
2444         else
2445                 used_strings = 0;
2446
2447         for (i = 0; i < used_strings; i++) {
2448                 guint token = decode_value (p, &p);
2449                 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
2450         }
2451
2452         if (amodule->info.opts & MONO_OPT_SHARED)       
2453                 keep_patches = FALSE;
2454
2455         n_patches = decode_value (p, &p);
2456
2457         keep_patches = FALSE;
2458
2459         if (n_patches) {
2460                 MonoJumpInfo *patches;
2461                 guint32 *got_slots;
2462
2463                 if (keep_patches)
2464                         mp = domain->mp;
2465                 else
2466                         mp = mono_mempool_new ();
2467
2468                 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
2469                 if (patches == NULL)
2470                         goto cleanup;
2471
2472                 for (pindex = 0; pindex < n_patches; ++pindex) {
2473                         MonoJumpInfo *ji = &patches [pindex];
2474
2475                         if (!amodule->got [got_slots [pindex]]) {
2476                                 amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
2477                                 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
2478                                         amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
2479                                 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
2480                                         register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
2481                         }
2482                         ji->type = MONO_PATCH_INFO_NONE;
2483                 }
2484
2485                 g_free (got_slots);
2486
2487                 if (!keep_patches)
2488                         mono_mempool_destroy (mp);
2489         }
2490
2491         if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2492                 char *full_name;
2493
2494                 if (!method)
2495                         method = mono_get_method (image, token, NULL);
2496
2497                 full_name = mono_method_full_name (method, TRUE);
2498
2499                 if (!jinfo)
2500                         jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
2501
2502                 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);
2503                 g_free (full_name);
2504         }
2505
2506         mono_aot_lock ();
2507
2508         mono_jit_stats.methods_aot++;
2509
2510         amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
2511
2512         init_plt (amodule);
2513
2514         if (method && method->wrapper_type)
2515                 g_hash_table_insert (amodule->method_to_code, method, code);
2516
2517         mono_aot_unlock ();
2518
2519         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
2520                 MonoJitInfo *jinfo;
2521
2522                 if (!method) {
2523                         method = mono_get_method (image, token, NULL);
2524                         g_assert (method);
2525                 }
2526                 mono_profiler_method_jit (method);
2527                 jinfo = mono_jit_info_table_find (domain, (char*)code);
2528                 g_assert (jinfo);
2529                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
2530         }
2531
2532         if (from_plt && klass && !klass->generic_container)
2533                 mono_runtime_class_init (mono_class_vtable (domain, klass));
2534
2535         return code;
2536
2537  cleanup:
2538         /* FIXME: The space in domain->mp is wasted */  
2539         if (amodule->info.opts & MONO_OPT_SHARED)
2540                 /* No need to cache patches */
2541                 mono_mempool_destroy (mp);
2542
2543         if (jinfo)
2544                 g_free (jinfo);
2545
2546         return NULL;
2547 }
2548
2549 static guint32
2550 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method, const char *name)
2551 {
2552         guint32 table_size, entry_size, hash;
2553         guint32 *table, *entry;
2554         guint32 index;
2555         static guint32 n_extra_decodes;
2556
2557         if (!amodule)
2558                 return 0xffffff;
2559
2560         table_size = amodule->extra_method_table [0];
2561         table = amodule->extra_method_table + 1;
2562         entry_size = 3;
2563
2564         hash = mono_aot_method_hash (method) % table_size;
2565
2566         entry = &table [hash * entry_size];
2567
2568         if (entry [0] == 0)
2569                 return 0xffffff;
2570
2571         index = 0xffffff;
2572         while (TRUE) {
2573                 guint32 key = entry [0];
2574                 guint32 value = entry [1];
2575                 guint32 next = entry [entry_size - 1];
2576                 MonoMethod *m;
2577                 guint8 *p;
2578                 int is_wrapper_name;
2579
2580                 p = amodule->blob + key;
2581                 is_wrapper_name = decode_value (p, &p);
2582                 if (is_wrapper_name) {
2583                         int wrapper_type = decode_value (p, &p);
2584                         if (wrapper_type == method->wrapper_type && !strcmp (name, (char*)p)) {
2585                                 index = value;
2586                                 break;
2587                         }
2588                 } else if (can_method_ref_match_method (amodule, p, method)) {
2589                         mono_aot_lock ();
2590                         if (!amodule->method_ref_to_method)
2591                                 amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
2592                         m = g_hash_table_lookup (amodule->method_ref_to_method, p);
2593                         mono_aot_unlock ();
2594                         if (!m) {
2595                                 guint8 *orig_p = p;
2596                                 m = decode_resolve_method_ref (amodule, p, &p);
2597                                 if (m) {
2598                                         mono_aot_lock ();
2599                                         g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
2600                                         mono_aot_unlock ();
2601                                 }
2602                         }
2603                         if (m == method) {
2604                                 index = value;
2605                                 break;
2606                         }
2607
2608                         /* Special case: wrappers of shared generic methods */
2609                         if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
2610                                 method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
2611                                 MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
2612                                 MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
2613
2614                                 if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
2615                                         index = value;
2616                                         break;
2617                                 }
2618                         }
2619
2620                         /* Methods decoded needlessly */
2621                         /*
2622                         if (m)
2623                                 printf ("%d %s %s\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE));
2624                         */
2625                         n_extra_decodes ++;
2626                 }
2627
2628                 if (next != 0)
2629                         entry = &table [next * entry_size];
2630                 else
2631                         break;
2632         }
2633
2634         return index;
2635 }
2636
2637 static void
2638 add_module_cb (gpointer key, gpointer value, gpointer user_data)
2639 {
2640         g_ptr_array_add ((GPtrArray*)user_data, value);
2641 }
2642
2643 /*
2644  * find_extra_method:
2645  *
2646  *   Try finding METHOD in the extra_method table in all AOT images.
2647  * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
2648  * module where the method was found.
2649  */
2650 static guint32
2651 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
2652 {
2653         guint32 index;
2654         GPtrArray *modules;
2655         int i;
2656         char *name = NULL;
2657
2658         if (method->wrapper_type)
2659                 name = mono_aot_wrapper_name (method);
2660
2661         /* Try the method's module first */
2662         *out_amodule = method->klass->image->aot_module;
2663         index = find_extra_method_in_amodule (method->klass->image->aot_module, method, name);
2664         if (index != 0xffffff) {
2665                 g_free (name);
2666                 return index;
2667         }
2668
2669         /* 
2670          * Try all other modules.
2671          * This is needed because generic instances klass->image points to the image
2672          * containing the generic definition, but the native code is generated to the
2673          * AOT image which contains the reference.
2674          */
2675
2676         /* Make a copy to avoid doing the search inside the aot lock */
2677         modules = g_ptr_array_new ();
2678         mono_aot_lock ();
2679         g_hash_table_foreach (aot_modules, add_module_cb, modules);
2680         mono_aot_unlock ();
2681
2682         index = 0xffffff;
2683         for (i = 0; i < modules->len; ++i) {
2684                 MonoAotModule *amodule = g_ptr_array_index (modules, i);
2685
2686                 if (amodule != method->klass->image->aot_module)
2687                         index = find_extra_method_in_amodule (amodule, method, name);
2688                 if (index != 0xffffff) {
2689                         *out_amodule = amodule;
2690                         break;
2691                 }
2692         }
2693         
2694         g_ptr_array_free (modules, TRUE);
2695
2696         g_free (name);
2697         return index;
2698 }
2699
2700 /*
2701  * mono_aot_get_method:
2702  *
2703  *   Return a pointer to the AOTed native code for METHOD if it can be found,
2704  * NULL otherwise.
2705  * On platforms with function pointers, this doesn't return a function pointer.
2706  */
2707 gpointer
2708 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
2709 {
2710         MonoClass *klass = method->klass;
2711         guint32 method_index;
2712         MonoAotModule *amodule = klass->image->aot_module;
2713         guint8 *code;
2714
2715         if (!amodule)
2716                 return NULL;
2717
2718         if (amodule->out_of_date)
2719                 return NULL;
2720
2721         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2722                 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2723                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2724                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2725                 return NULL;
2726
2727         /*
2728          * Use the original method instead of its invoke-with-check wrapper.
2729          * This is not a problem when using full-aot, since it doesn't support
2730          * remoting.
2731          */
2732         if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
2733                 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));
2734
2735         g_assert (klass->inited);
2736
2737         /* Find method index */
2738         if (method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE)) {
2739                 /* 
2740                  * For generic methods, we store the fully shared instance in place of the
2741                  * original method.
2742                  */
2743                 method = mono_method_get_declaring_generic_method (method);
2744                 method_index = mono_metadata_token_index (method->token) - 1;
2745         } else if (method->is_inflated || !method->token) {
2746                 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
2747                 mono_aot_lock ();
2748                 code = g_hash_table_lookup (amodule->method_to_code, method);
2749                 mono_aot_unlock ();
2750                 if (code)
2751                         return code;
2752
2753                 method_index = find_extra_method (method, &amodule);
2754                 /*
2755                  * Special case the ICollection<T> wrappers for arrays, as they cannot
2756                  * be statically enumerated, and each wrapper ends up calling the same
2757                  * method in Array.
2758                  */
2759                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
2760                         MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2761
2762                         code = mono_aot_get_method (domain, m);
2763                         if (code) {
2764                                 if (mono_method_needs_static_rgctx_invoke (m, FALSE)) {
2765                                         code = mono_create_static_rgctx_trampoline (m, mono_create_ftnptr (domain, code));
2766                                         /* The call above returns an ftnptr */
2767                                         code = mono_get_addr_from_ftnptr (code);
2768                                 }
2769
2770                                 return code;
2771                         }
2772                 }
2773
2774                 /*
2775                  * Special case Array.GetGenericValueImpl which is a generic icall.
2776                  * Generic sharing currently can't handle it, but the icall returns data using
2777                  * an out parameter, so the managed-to-native wrappers can share the same code.
2778                  */
2779                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
2780                         MonoMethod *m;
2781                         MonoGenericContext ctx;
2782                         MonoType *args [16];
2783
2784                         if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
2785                                 /* Avoid recursion */
2786                                 return NULL;
2787
2788                         m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
2789                         g_assert (m);
2790
2791                         memset (&ctx, 0, sizeof (ctx));
2792                         args [0] = &mono_defaults.object_class->byval_arg;
2793                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2794
2795                         m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
2796
2797                         /* 
2798                          * Get the code for the <object> instantiation which should be emitted into
2799                          * the mscorlib aot image by the AOT compiler.
2800                          */
2801                         code = mono_aot_get_method (domain, m);
2802                         if (code)
2803                                 return code;
2804                 }
2805
2806                 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, TRUE)) {
2807                         /* Partial sharing */
2808                         method_index = find_extra_method (mini_get_shared_method (method), &amodule);
2809                 }
2810
2811                 if (method_index == 0xffffff) {
2812                         if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2813                                 char *full_name;
2814
2815                                 full_name = mono_method_full_name (method, TRUE);
2816                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
2817                                 g_free (full_name);
2818                         }
2819                         return NULL;
2820                 }
2821
2822                 if (method_index == 0xffffff)
2823                         return NULL;
2824
2825                 /* Needed by find_jit_info */
2826                 mono_aot_lock ();
2827                 if (!amodule->extra_methods)
2828                         amodule->extra_methods = g_hash_table_new (NULL, NULL);
2829                 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
2830                 mono_aot_unlock ();
2831         } else {
2832                 /* Common case */
2833                 method_index = mono_metadata_token_index (method->token) - 1;
2834         }
2835
2836         return load_method (domain, amodule, klass->image, method, method->token, method_index);
2837 }
2838
2839 /**
2840  * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
2841  * method.
2842  */
2843 gpointer
2844 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
2845 {
2846         MonoAotModule *aot_module = image->aot_module;
2847         int method_index;
2848
2849         if (!aot_module)
2850                 return NULL;
2851
2852         method_index = mono_metadata_token_index (token) - 1;
2853
2854         return load_method (domain, aot_module, image, NULL, token, method_index);
2855 }
2856
2857 typedef struct {
2858         guint8 *addr;
2859         gboolean res;
2860 } IsGotEntryUserData;
2861
2862 static void
2863 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
2864 {
2865         IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
2866         MonoAotModule *aot_module = (MonoAotModule*)value;
2867
2868         if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
2869                 data->res = TRUE;
2870 }
2871
2872 gboolean
2873 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
2874 {
2875         IsGotEntryUserData user_data;
2876
2877         if (!aot_modules)
2878                 return FALSE;
2879
2880         user_data.addr = addr;
2881         user_data.res = FALSE;
2882         mono_aot_lock ();
2883         g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
2884         mono_aot_unlock ();
2885         
2886         return user_data.res;
2887 }
2888
2889 typedef struct {
2890         guint8 *addr;
2891         MonoAotModule *module;
2892 } FindAotModuleUserData;
2893
2894 static void
2895 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
2896 {
2897         FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
2898         MonoAotModule *aot_module = (MonoAotModule*)value;
2899
2900         if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
2901                 data->module = aot_module;
2902 }
2903
2904 static inline MonoAotModule*
2905 find_aot_module (guint8 *code)
2906 {
2907         FindAotModuleUserData user_data;
2908
2909         if (!aot_modules)
2910                 return NULL;
2911
2912         /* Reading these need no locking */
2913         if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
2914                 return NULL;
2915
2916         user_data.addr = code;
2917         user_data.module = NULL;
2918                 
2919         mono_aot_lock ();
2920         g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
2921         mono_aot_unlock ();
2922         
2923         return user_data.module;
2924 }
2925
2926 void
2927 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
2928 {
2929         /*
2930          * Since AOT code is only used in the root domain, 
2931          * mono_domain_get () != mono_get_root_domain () means the calling method
2932          * is AppDomain:InvokeInDomain, so this is the same check as in 
2933          * mono_method_same_domain () but without loading the metadata for the method.
2934          */
2935         if (mono_domain_get () == mono_get_root_domain ())
2936                 mono_arch_patch_plt_entry (code, got, regs, addr);
2937 }
2938
2939 /*
2940  * mono_aot_plt_resolve:
2941  *
2942  *   This function is called by the entries in the PLT to resolve the actual method that
2943  * needs to be called. It returns a trampoline to the method and patches the PLT entry.
2944  * Returns NULL if the something cannot be loaded.
2945  */
2946 gpointer
2947 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
2948 {
2949 #ifdef MONO_ARCH_AOT_SUPPORTED
2950         guint8 *p, *target, *plt_entry;
2951         MonoJumpInfo ji;
2952         MonoAotModule *module = (MonoAotModule*)aot_module;
2953         gboolean res, no_ftnptr = FALSE;
2954         MonoMemPool *mp;
2955
2956         //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
2957
2958         p = &module->blob [plt_info_offset];
2959
2960         ji.type = decode_value (p, &p);
2961
2962         mp = mono_mempool_new_size (512);
2963         res = decode_patch (module, mp, &ji, p, &p);
2964
2965         if (!res) {
2966                 mono_mempool_destroy (mp);
2967                 return NULL;
2968         }
2969
2970         /* 
2971          * Avoid calling resolve_patch_target in the full-aot case if possible, since
2972          * it would create a trampoline, and we don't need that.
2973          * We could do this only if the method does not need the special handling
2974          * in mono_magic_trampoline ().
2975          */
2976         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) &&
2977                 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE)) {
2978                 target = mono_jit_compile_method (ji.data.method);
2979                 no_ftnptr = TRUE;
2980         } else {
2981                 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
2982         }
2983
2984         /*
2985          * The trampoline expects us to return a function descriptor on platforms which use
2986          * it, but resolve_patch_target returns a direct function pointer for some type of
2987          * patches, so have to translate between the two.
2988          * FIXME: Clean this up, but how ?
2989          */
2990         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) {
2991                 /* These should already have a function descriptor */
2992 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2993                 /* Our function descriptors have a 0 environment, gcc created ones don't */
2994                 if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
2995                         g_assert (((gpointer*)target) [2] == 0);
2996 #endif
2997                 /* Empty */
2998         } else if (!no_ftnptr) {
2999 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3000                 g_assert (((gpointer*)target) [2] != 0);
3001 #endif
3002                 target = mono_create_ftnptr (mono_domain_get (), target);
3003         }
3004
3005         mono_mempool_destroy (mp);
3006
3007         /* Patch the PLT entry with target which might be the actual method not a trampoline */
3008         plt_entry = mono_aot_get_plt_entry (code);
3009         g_assert (plt_entry);
3010         mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target);
3011
3012         return target;
3013 #else
3014         g_assert_not_reached ();
3015         return NULL;
3016 #endif
3017 }
3018
3019 /**
3020  * init_plt:
3021  *
3022  *   Initialize the PLT table of the AOT module. Called lazily when the first AOT
3023  * method in the module is loaded to avoid committing memory by writing to it.
3024  * LOCKING: Assumes the AOT lock is held.
3025  */
3026 static void
3027 init_plt (MonoAotModule *amodule)
3028 {
3029         int i;
3030         gpointer tramp;
3031
3032         if (amodule->plt_inited)
3033                 return;
3034
3035         tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
3036
3037         /*
3038          * Initialize the PLT entries in the GOT to point to the default targets.
3039          */
3040
3041         tramp = mono_create_ftnptr (mono_domain_get (), tramp);
3042          for (i = 1; i < amodule->info.plt_size; ++i)
3043                  /* All the default entries point to the AOT trampoline */
3044                  ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
3045
3046         amodule->plt_inited = TRUE;
3047 }
3048
3049 /*
3050  * mono_aot_get_plt_entry:
3051  *
3052  *   Return the address of the PLT entry called by the code at CODE if exists.
3053  */
3054 guint8*
3055 mono_aot_get_plt_entry (guint8 *code)
3056 {
3057         MonoAotModule *aot_module = find_aot_module (code);
3058
3059         if (!aot_module)
3060                 return NULL;
3061
3062 #ifdef MONO_ARCH_AOT_SUPPORTED
3063         {
3064                 guint8 *target = mono_arch_get_call_target (code);
3065
3066                 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
3067                         return target;
3068         }
3069 #else
3070         g_assert_not_reached ();
3071 #endif
3072
3073         return NULL;
3074 }
3075
3076 /*
3077  * mono_aot_get_plt_info_offset:
3078  *
3079  *   Return the PLT info offset belonging to the plt entry called by CODE.
3080  */
3081 guint32
3082 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3083 {
3084         guint8 *plt_entry = mono_aot_get_plt_entry (code);
3085
3086         g_assert (plt_entry);
3087
3088         /* The offset is embedded inside the code after the plt entry */
3089 #ifdef MONO_ARCH_AOT_SUPPORTED
3090         return mono_arch_get_plt_info_offset (plt_entry, regs, code);
3091 #else
3092         g_assert_not_reached ();
3093         return 0;
3094 #endif
3095 }
3096
3097 static gpointer
3098 mono_create_ftnptr_malloc (guint8 *code)
3099 {
3100 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3101         MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
3102
3103         ftnptr->code = code;
3104         ftnptr->toc = NULL;
3105         ftnptr->env = NULL;
3106
3107         return ftnptr;
3108 #else
3109         return code;
3110 #endif
3111 }
3112
3113 static GHashTable *aot_jit_icall_hash;
3114
3115 /*
3116  * mono_aot_register_jit_icall:
3117  *
3118  *   Register a JIT icall which is called by trampolines in full-aot mode. This should
3119  * be called from mono_arch_init () during startup.
3120  */
3121 void
3122 mono_aot_register_jit_icall (const char *name, gpointer addr)
3123 {
3124         /* No need for locking */
3125         if (!aot_jit_icall_hash)
3126                 aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
3127         g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
3128 }
3129
3130 /*
3131  * load_function:
3132  *
3133  *   Load the function named NAME from the aot image. 
3134  */
3135 static gpointer
3136 load_function (MonoAotModule *amodule, const char *name)
3137 {
3138         char *symbol;
3139         guint8 *p;
3140         int n_patches, pindex;
3141         MonoMemPool *mp;
3142         gpointer code;
3143
3144         /* Load the code */
3145
3146         symbol = g_strdup_printf ("%s", name);
3147         find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
3148         g_free (symbol);
3149         if (!code)
3150                 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
3151
3152         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.\n", name, amodule->aot_name);
3153
3154         /* Load info */
3155
3156         symbol = g_strdup_printf ("%s_p", name);
3157         find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
3158         g_free (symbol);
3159         if (!p)
3160                 /* Nothing to patch */
3161                 return code;
3162
3163         p = amodule->blob + *(guint32*)p;
3164
3165         /* Similar to mono_aot_load_method () */
3166
3167         n_patches = decode_value (p, &p);
3168
3169         if (n_patches) {
3170                 MonoJumpInfo *patches;
3171                 guint32 *got_slots;
3172
3173                 mp = mono_mempool_new ();
3174
3175                 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3176                 g_assert (patches);
3177
3178                 for (pindex = 0; pindex < n_patches; ++pindex) {
3179                         MonoJumpInfo *ji = &patches [pindex];
3180                         gpointer target;
3181
3182                         if (amodule->got [got_slots [pindex]])
3183                                 continue;
3184
3185                         /*
3186                          * When this code is executed, the runtime may not be initalized yet, so
3187                          * resolve the patch info by hand.
3188                          */
3189                         if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
3190                                 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
3191                                         target = mono_get_lmf_addr;
3192                                 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
3193                                         target = mono_thread_force_interruption_checkpoint;
3194                                 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
3195                                         target = mono_exception_from_token;
3196                                 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
3197                                         target = mono_get_throw_exception ();
3198                                 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
3199                                         int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
3200                                         target = (gpointer)mono_get_trampoline_func (tramp_type2);
3201                                 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
3202                                         /* atoll is needed because the the offset is unsigned */
3203                                         guint32 slot;
3204                                         int res;
3205
3206                                         res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
3207                                         g_assert (res == 1);
3208                                         target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
3209                                         target = mono_create_ftnptr_malloc (target);
3210                                 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
3211                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
3212                                         target = mono_create_ftnptr_malloc (target);
3213                                 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
3214                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
3215                                         target = mono_create_ftnptr_malloc (target);
3216                                 } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
3217                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
3218                                         target = mono_create_ftnptr_malloc (target);
3219                                 } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
3220                                         target = mono_thread_get_and_clear_pending_exception;
3221                                 } else if (strstr (ji->data.name, "generic_trampoline_monitor_enter")) {
3222                                         char *symbol;
3223
3224                                         symbol = g_strdup_printf ("generic_trampoline_%d", MONO_TRAMPOLINE_MONITOR_ENTER);
3225                                         target = mono_aot_get_trampoline (symbol);
3226                                         g_free (symbol);
3227                                 } else if (strstr (ji->data.name, "generic_trampoline_monitor_exit")) {
3228                                         char *symbol;
3229
3230                                         symbol = g_strdup_printf ("generic_trampoline_%d", MONO_TRAMPOLINE_MONITOR_EXIT);
3231                                         target = mono_aot_get_trampoline (symbol);
3232                                         g_free (symbol);
3233                                 } else if (strstr (ji->data.name, "generic_trampoline_generic_class_init")) {
3234                                         char *symbol;
3235
3236                                         symbol = g_strdup_printf ("generic_trampoline_%d", MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
3237                                         target = mono_aot_get_trampoline (symbol);
3238                                         g_free (symbol);
3239                                 } else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
3240                                         /* Registered by mono_arch_init () */
3241                                         target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
3242                                 } else {
3243                                         fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
3244                                         g_assert_not_reached ();
3245                                         target = NULL;
3246                                 }
3247                         } else {
3248                                 /* Hopefully the code doesn't have patches which need method or 
3249                                  * domain to be set.
3250                                  */
3251                                 target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
3252                                 g_assert (target);
3253                         }
3254
3255                         amodule->got [got_slots [pindex]] = target;
3256                 }
3257
3258                 g_free (got_slots);
3259
3260                 mono_mempool_destroy (mp);
3261         }
3262
3263         return code;
3264 }
3265
3266 /*
3267  * Return the trampoline identified by NAME from the mscorlib AOT file.
3268  * On ppc64, this returns a function descriptor.
3269  */
3270 gpointer
3271 mono_aot_get_trampoline (const char *name)
3272 {
3273         MonoImage *image;
3274         MonoAotModule *amodule;
3275
3276         image = mono_defaults.corlib;
3277         g_assert (image);
3278
3279         amodule = image->aot_module;
3280         g_assert (amodule);
3281
3282         return mono_create_ftnptr_malloc (load_function (amodule, name));
3283 }
3284
3285 /* Return a given kind of trampoline */
3286 static gpointer
3287 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
3288 {
3289         MonoAotModule *amodule;
3290         int index, tramp_size;
3291         MonoImage *image;
3292
3293         /* Currently, we keep all trampolines in the mscorlib AOT image */
3294         image = mono_defaults.corlib;
3295         g_assert (image);
3296
3297         mono_aot_lock ();
3298
3299         amodule = image->aot_module;
3300         g_assert (amodule);
3301
3302         *out_amodule = amodule;
3303
3304         if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type])
3305                 g_error ("Ran out of trampolines of type %d in '%s' (%d)\n", tramp_type, image->name, amodule->info.num_trampolines [tramp_type]);
3306
3307         index = amodule->trampoline_index [tramp_type] ++;
3308
3309         mono_aot_unlock ();
3310
3311         *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
3312
3313         tramp_size = amodule->info.trampoline_size [tramp_type];
3314
3315         if (out_tramp_size)
3316                 *out_tramp_size = tramp_size;
3317
3318         return amodule->trampolines [tramp_type] + (index * tramp_size);
3319 }
3320
3321 /*
3322  * Return a specific trampoline from the AOT file.
3323  */
3324 gpointer
3325 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
3326 {
3327         MonoAotModule *amodule;
3328         guint32 got_offset, tramp_size;
3329         guint8 *code, *tramp;
3330         static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
3331         static gboolean inited;
3332         static guint32 num_trampolines;
3333
3334         if (!inited) {
3335                 mono_aot_lock ();
3336
3337                 if (!inited) {
3338                         mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
3339                         inited = TRUE;
3340                 }
3341
3342                 mono_aot_unlock ();
3343         }
3344
3345         num_trampolines ++;
3346
3347         if (!generic_trampolines [tramp_type]) {
3348                 char *symbol;
3349
3350                 symbol = g_strdup_printf ("generic_trampoline_%d", tramp_type);
3351                 generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
3352                 g_free (symbol);
3353         }
3354
3355         tramp = generic_trampolines [tramp_type];
3356         g_assert (tramp);
3357
3358         code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
3359
3360         amodule->got [got_offset] = tramp;
3361         amodule->got [got_offset + 1] = arg1;
3362
3363         if (code_len)
3364                 *code_len = tramp_size;
3365
3366         return code;
3367 }
3368
3369 gpointer
3370 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
3371 {
3372         MonoAotModule *amodule;
3373         guint8 *code;
3374         guint32 got_offset;
3375
3376         code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
3377
3378         amodule->got [got_offset] = ctx;
3379         amodule->got [got_offset + 1] = addr; 
3380
3381         /* The caller expects an ftnptr */
3382         return mono_create_ftnptr (mono_domain_get (), code);
3383 }
3384
3385 gpointer
3386 mono_aot_get_unbox_trampoline (MonoMethod *method)
3387 {
3388         guint32 method_index = mono_metadata_token_index (method->token) - 1;
3389         MonoAotModule *amodule;
3390         char *symbol;
3391         gpointer code;
3392
3393         if (method->is_inflated && !mono_method_is_generic_sharable_impl (method, FALSE)) {
3394                 guint32 index = find_extra_method (method, &amodule);
3395                 g_assert (index != 0xffffff);
3396                 
3397                 symbol = g_strdup_printf ("ut_e_%d", index);
3398         } else {
3399                 amodule = method->klass->image->aot_module;
3400                 g_assert (amodule);
3401
3402                 symbol = g_strdup_printf ("ut_%d", method_index);
3403         }
3404         code = load_function (amodule, symbol);
3405         g_free (symbol);
3406
3407         /* The caller expects an ftnptr */
3408         return mono_create_ftnptr (mono_domain_get (), code);
3409 }
3410
3411 gpointer
3412 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
3413 {
3414         char *symbol;
3415         gpointer code;
3416
3417         symbol = g_strdup_printf ("rgctx_fetch_trampoline_%u", slot);
3418         code = load_function (mono_defaults.corlib->aot_module, symbol);
3419         g_free (symbol);
3420         /* The caller expects an ftnptr */
3421         return mono_create_ftnptr (mono_domain_get (), code);
3422 }
3423
3424 gpointer
3425 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
3426 {
3427         guint32 got_offset;
3428         gpointer code;
3429         gpointer *buf;
3430         int i;
3431         MonoAotModule *amodule;
3432
3433         code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
3434
3435         /* Save the entries into an array */
3436         buf = mono_domain_alloc (domain, (count + 1) * 2 * sizeof (gpointer));
3437         for (i = 0; i < count; ++i) {
3438                 MonoIMTCheckItem *item = imt_entries [i];               
3439
3440                 g_assert (item->key);
3441                 /* FIXME: */
3442                 g_assert (!item->has_target_code);
3443
3444                 buf [(i * 2)] = item->key;
3445                 buf [(i * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
3446         }
3447         buf [(count * 2)] = NULL;
3448         buf [(count * 2) + 1] = fail_tramp;
3449         
3450         amodule->got [got_offset] = buf;
3451
3452         return code;
3453 }
3454  
3455 /*
3456  * mono_aot_set_make_unreadable:
3457  *
3458  *   Set whenever to make all mmaped memory unreadable. In conjuction with a
3459  * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
3460  */
3461 void
3462 mono_aot_set_make_unreadable (gboolean unreadable)
3463 {
3464         static int inited;
3465
3466         make_unreadable = unreadable;
3467
3468         if (make_unreadable && !inited) {
3469                 mono_counters_register ("AOT pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
3470         }               
3471 }
3472
3473 typedef struct {
3474         MonoAotModule *module;
3475         guint8 *ptr;
3476 } FindMapUserData;
3477
3478 static void
3479 find_map (gpointer key, gpointer value, gpointer user_data)
3480 {
3481         MonoAotModule *module = (MonoAotModule*)value;
3482         FindMapUserData *data = (FindMapUserData*)user_data;
3483
3484         if (!data->module)
3485                 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
3486                         data->module = module;
3487 }
3488
3489 static MonoAotModule*
3490 find_module_for_addr (void *ptr)
3491 {
3492         FindMapUserData data;
3493
3494         if (!make_unreadable)
3495                 return NULL;
3496
3497         data.module = NULL;
3498         data.ptr = (guint8*)ptr;
3499
3500         mono_aot_lock ();
3501         g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
3502         mono_aot_unlock ();
3503
3504         return data.module;
3505 }
3506
3507 /*
3508  * mono_aot_is_pagefault:
3509  *
3510  *   Should be called from a SIGSEGV signal handler to find out whenever @ptr is
3511  * within memory allocated by this module.
3512  */
3513 gboolean
3514 mono_aot_is_pagefault (void *ptr)
3515 {
3516         if (!make_unreadable)
3517                 return FALSE;
3518
3519         /* 
3520          * Not signal safe, but SIGSEGV's are synchronous, and
3521          * this is only turned on by a MONO_DEBUG option.
3522          */
3523         return find_module_for_addr (ptr) != NULL;
3524 }
3525
3526 /*
3527  * mono_aot_handle_pagefault:
3528  *
3529  *   Handle a pagefault caused by an unreadable page by making it readable again.
3530  */
3531 void
3532 mono_aot_handle_pagefault (void *ptr)
3533 {
3534 #ifndef PLATFORM_WIN32
3535         guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
3536         int res;
3537
3538         mono_aot_lock ();
3539         res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
3540         g_assert (res == 0);
3541
3542         n_pagefaults ++;
3543         mono_aot_unlock ();
3544 #endif
3545 }
3546
3547 #else
3548 /* AOT disabled */
3549
3550 void
3551 mono_aot_init (void)
3552 {
3553 }
3554
3555 gpointer
3556 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
3557 {
3558         return NULL;
3559 }
3560
3561 gboolean
3562 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3563 {
3564         return FALSE;
3565 }
3566
3567 gboolean
3568 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
3569 {
3570         return FALSE;
3571 }
3572
3573 gboolean
3574 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
3575 {
3576         return FALSE;
3577 }
3578
3579 MonoJitInfo *
3580 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
3581 {
3582         return NULL;
3583 }
3584
3585 gpointer
3586 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3587 {
3588         return NULL;
3589 }
3590
3591 guint8*
3592 mono_aot_get_plt_entry (guint8 *code)
3593 {
3594         return NULL;
3595 }
3596
3597 gpointer
3598 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3599 {
3600         return NULL;
3601 }
3602
3603 void
3604 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
3605 {
3606 }
3607
3608 gpointer
3609 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
3610 {
3611         return NULL;
3612 }
3613
3614 guint32
3615 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3616 {
3617         g_assert_not_reached ();
3618
3619         return 0;
3620 }
3621
3622 gpointer
3623 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
3624 {
3625         g_assert_not_reached ();
3626         return NULL;
3627 }
3628
3629 gpointer
3630 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
3631 {
3632         g_assert_not_reached ();
3633         return NULL;
3634 }
3635
3636 gpointer
3637 mono_aot_get_trampoline (const char *name)
3638 {
3639         g_assert_not_reached ();
3640         return NULL;
3641 }
3642
3643 gpointer
3644 mono_aot_get_unbox_trampoline (MonoMethod *method)
3645 {
3646         g_assert_not_reached ();
3647         return NULL;
3648 }
3649
3650 gpointer
3651 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
3652 {
3653         g_assert_not_reached ();
3654         return NULL;
3655 }
3656
3657 gpointer
3658 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
3659 {
3660         g_assert_not_reached ();
3661         return NULL;
3662 }       
3663
3664 guint8*
3665 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
3666 {
3667         g_assert_not_reached ();
3668         return NULL;
3669 }
3670
3671 void
3672 mono_aot_register_jit_icall (const char *name, gpointer addr)
3673 {
3674 }
3675
3676 #endif