Clean up the code which handles prepending _ to global symbol names on MACH by doing...
[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  * Copyright 2003-2011 Novell, Inc.
10  * Copyright 2011 Xamarin, Inc.
11  */
12
13 #include "config.h"
14 #include <sys/types.h>
15 #ifdef HAVE_UNISTD_H
16 #include <unistd.h>
17 #endif
18 #include <fcntl.h>
19 #include <string.h>
20 #ifdef HAVE_SYS_MMAN_H
21 #include <sys/mman.h>
22 #endif
23
24 #if HOST_WIN32
25 #include <winsock2.h>
26 #include <windows.h>
27 #endif
28
29 #ifdef HAVE_EXECINFO_H
30 #include <execinfo.h>
31 #endif
32
33 #include <errno.h>
34 #include <sys/stat.h>
35
36 #ifdef HAVE_SYS_WAIT_H
37 #include <sys/wait.h>  /* for WIFEXITED, WEXITSTATUS */
38 #endif
39
40 #include <mono/metadata/tabledefs.h>
41 #include <mono/metadata/class.h>
42 #include <mono/metadata/object.h>
43 #include <mono/metadata/tokentype.h>
44 #include <mono/metadata/appdomain.h>
45 #include <mono/metadata/debug-helpers.h>
46 #include <mono/metadata/assembly.h>
47 #include <mono/metadata/metadata-internals.h>
48 #include <mono/metadata/marshal.h>
49 #include <mono/metadata/gc-internal.h>
50 #include <mono/metadata/monitor.h>
51 #include <mono/metadata/threads-types.h>
52 #include <mono/metadata/mono-endian.h>
53 #include <mono/utils/mono-logger-internal.h>
54 #include <mono/utils/mono-mmap.h>
55 #include "mono/utils/mono-compiler.h"
56 #include <mono/utils/mono-counters.h>
57
58 #include "mini.h"
59 #include "version.h"
60
61 #ifndef DISABLE_AOT
62
63 #ifdef TARGET_WIN32
64 #define SHARED_EXT ".dll"
65 #elif ((defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__)) || defined(__MACH__)) && !defined(__linux__)
66 #define SHARED_EXT ".dylib"
67 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
68 #define SHARED_EXT ".dylib"
69 #else
70 #define SHARED_EXT ".so"
71 #endif
72
73 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
74 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
75
76 typedef struct MonoAotModule {
77         char *aot_name;
78         /* Pointer to the Global Offset Table */
79         gpointer *got;
80         GHashTable *name_cache;
81         GHashTable *extra_methods;
82         /* Maps methods to their code */
83         GHashTable *method_to_code;
84         /* Maps pointers into the method info to the methods themselves */
85         GHashTable *method_ref_to_method;
86         MonoAssemblyName *image_names;
87         char **image_guids;
88         MonoAssembly *assembly;
89         MonoImage **image_table;
90         guint32 image_table_len;
91         gboolean out_of_date;
92         gboolean plt_inited;
93         guint8 *mem_begin;
94         guint8 *mem_end;
95         guint8 *code;
96         guint8 *code_end;
97         guint8 *plt;
98         guint8 *plt_end;
99         guint8 *blob;
100         gint32 *code_offsets;
101 #ifdef MONOTOUCH
102         gpointer *method_addresses;
103 #endif
104         /* This contains <offset, index> pairs sorted by offset */
105         /* This is needed because LLVM emitted methods can be in any order */
106         gint32 *sorted_code_offsets;
107         gint32 sorted_code_offsets_len;
108         guint32 *method_info_offsets;
109         guint32 *got_info_offsets;
110         guint32 *ex_info_offsets;
111         guint32 *class_info_offsets;
112         guint32 *methods_loaded;
113         guint16 *class_name_table;
114         guint32 *extra_method_table;
115         guint32 *extra_method_info_offsets;
116         guint32 *unbox_trampolines;
117         guint32 *unbox_trampolines_end;
118         guint8 *unwind_info;
119         guint8 *thumb_end;
120
121         /* Points to the mono EH data created by LLVM */
122         guint8 *mono_eh_frame;
123
124         /* Points to the trampolines */
125         guint8 *trampolines [MONO_AOT_TRAMP_NUM];
126         /* The first unused trampoline of each kind */
127         guint32 trampoline_index [MONO_AOT_TRAMP_NUM];
128
129         gboolean use_page_trampolines;
130
131         MonoAotFileInfo info;
132
133         gpointer *globals;
134         MonoDl *sofile;
135 } MonoAotModule;
136
137 typedef struct {
138         void *next;
139         unsigned char *trampolines;
140         unsigned char *trampolines_end;
141 } TrampolinePage;
142
143 static GHashTable *aot_modules;
144 #define mono_aot_lock() EnterCriticalSection (&aot_mutex)
145 #define mono_aot_unlock() LeaveCriticalSection (&aot_mutex)
146 static CRITICAL_SECTION aot_mutex;
147
148 /* 
149  * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
150  * AOT modules registered by mono_aot_register_module ().
151  */
152 static GHashTable *static_aot_modules;
153
154 /*
155  * Maps MonoJitInfo* to the aot module they belong to, this can be different
156  * from ji->method->klass->image's aot module for generic instances.
157  */
158 static GHashTable *ji_to_amodule;
159
160 /*
161  * Whenever to AOT compile loaded assemblies on demand and store them in
162  * a cache under $HOME/.mono/aot-cache.
163  */
164 static gboolean use_aot_cache = FALSE;
165
166 /*
167  * Whenever to spawn a new process to AOT a file or do it in-process. Only relevant if
168  * use_aot_cache is TRUE.
169  */
170 static gboolean spawn_compiler = TRUE;
171
172 /* For debugging */
173 static gint32 mono_last_aot_method = -1;
174
175 static gboolean make_unreadable = FALSE;
176 static guint32 name_table_accesses = 0;
177 static guint32 n_pagefaults = 0;
178
179 /* Used to speed-up find_aot_module () */
180 static gsize aot_code_low_addr = (gssize)-1;
181 static gsize aot_code_high_addr = 0;
182
183 static GHashTable *aot_jit_icall_hash;
184
185 #ifdef MONOTOUCH
186 #define USE_PAGE_TRAMPOLINES ((MonoAotModule*)mono_defaults.corlib->aot_module)->use_page_trampolines
187 #else
188 #define USE_PAGE_TRAMPOLINES 0
189 #endif
190
191 #define mono_aot_page_lock() EnterCriticalSection (&aot_page_mutex)
192 #define mono_aot_page_unlock() LeaveCriticalSection (&aot_page_mutex)
193 static CRITICAL_SECTION aot_page_mutex;
194
195 static void
196 init_plt (MonoAotModule *info);
197
198 /*****************************************************/
199 /*                 AOT RUNTIME                       */
200 /*****************************************************/
201
202 /*
203  * load_image:
204  *
205  *   Load one of the images referenced by AMODULE. Returns NULL if the image is not
206  * found, and sets the loader error if SET_ERROR is TRUE.
207  */
208 static MonoImage *
209 load_image (MonoAotModule *amodule, int index, gboolean set_error)
210 {
211         MonoAssembly *assembly;
212         MonoImageOpenStatus status;
213
214         g_assert (index < amodule->image_table_len);
215
216         if (amodule->image_table [index])
217                 return amodule->image_table [index];
218         if (amodule->out_of_date)
219                 return NULL;
220
221         assembly = mono_assembly_load (&amodule->image_names [index], amodule->assembly->basedir, &status);
222         if (!assembly) {
223                 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);
224                 amodule->out_of_date = TRUE;
225
226                 if (set_error) {
227                         char *full_name = mono_stringify_assembly_name (&amodule->image_names [index]);
228                         mono_loader_set_error_assembly_load (full_name, FALSE);
229                         g_free (full_name);
230                 }
231                 return NULL;
232         }
233
234         if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
235                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable (GUID of dependent assembly %s doesn't match (expected '%s', got '%s').\n", amodule->aot_name, amodule->image_names [index].name, amodule->image_guids [index], assembly->image->guid);
236                 amodule->out_of_date = TRUE;
237                 return NULL;
238         }
239
240         amodule->image_table [index] = assembly->image;
241         return assembly->image;
242 }
243
244 static inline gint32
245 decode_value (guint8 *ptr, guint8 **rptr)
246 {
247         guint8 b = *ptr;
248         gint32 len;
249         
250         if ((b & 0x80) == 0){
251                 len = b;
252                 ++ptr;
253         } else if ((b & 0x40) == 0){
254                 len = ((b & 0x3f) << 8 | ptr [1]);
255                 ptr += 2;
256         } else if (b != 0xff) {
257                 len = ((b & 0x1f) << 24) |
258                         (ptr [1] << 16) |
259                         (ptr [2] << 8) |
260                         ptr [3];
261                 ptr += 4;
262         }
263         else {
264                 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
265                 ptr += 5;
266         }
267         if (rptr)
268                 *rptr = ptr;
269
270         //printf ("DECODE: %d.\n", len);
271         return len;
272 }
273
274 /*
275  * mono_aot_get_offset:
276  *
277  *   Decode an offset table emitted by emit_offset_table (), returning the INDEXth
278  * entry.
279  */
280 static guint32
281 mono_aot_get_offset (guint32 *table, int index)
282 {
283         int i, group, ngroups, index_entry_size;
284         int start_offset, offset, noffsets, group_size;
285         guint8 *data_start, *p;
286         guint32 *index32 = NULL;
287         guint16 *index16 = NULL;
288         
289         noffsets = table [0];
290         group_size = table [1];
291         ngroups = table [2];
292         index_entry_size = table [3];
293         group = index / group_size;
294
295         if (index_entry_size == 2) {
296                 index16 = (guint16*)&table [4];
297                 data_start = (guint8*)&index16 [ngroups];
298                 p = data_start + index16 [group];
299         } else {
300                 index32 = (guint32*)&table [4];
301                 data_start = (guint8*)&index32 [ngroups];
302                 p = data_start + index32 [group];
303         }
304
305         /* offset will contain the value of offsets [group * group_size] */
306         offset = start_offset = decode_value (p, &p);
307         for (i = group * group_size + 1; i <= index; ++i) {
308                 offset += decode_value (p, &p);
309         }
310
311         //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
312
313         return offset;
314 }
315
316 static MonoMethod*
317 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
318
319 static MonoClass*
320 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
321
322 static MonoType*
323 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
324
325 static MonoGenericInst*
326 decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
327 {
328         int type_argc, i;
329         MonoType **type_argv;
330         MonoGenericInst *inst;
331         guint8 *p = buf;
332
333         type_argc = decode_value (p, &p);
334         type_argv = g_new0 (MonoType*, type_argc);
335
336         for (i = 0; i < type_argc; ++i) {
337                 MonoClass *pclass = decode_klass_ref (module, p, &p);
338                 if (!pclass) {
339                         g_free (type_argv);
340                         return NULL;
341                 }
342                 type_argv [i] = &pclass->byval_arg;
343         }
344
345         inst = mono_metadata_get_generic_inst (type_argc, type_argv);
346         g_free (type_argv);
347
348         *endbuf = p;
349
350         return inst;
351 }
352
353 static gboolean
354 decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf)
355 {
356         guint8 *p = buf;
357         guint8 *p2;
358         int argc;
359
360         p2 = p;
361         argc = decode_value (p, &p);
362         if (argc) {
363                 p = p2;
364                 ctx->class_inst = decode_generic_inst (module, p, &p);
365                 if (!ctx->class_inst)
366                         return FALSE;
367         }
368         p2 = p;
369         argc = decode_value (p, &p);
370         if (argc) {
371                 p = p2;
372                 ctx->method_inst = decode_generic_inst (module, p, &p);
373                 if (!ctx->method_inst)
374                         return FALSE;
375         }
376
377         *endbuf = p;
378         return TRUE;
379 }
380
381 static MonoClass*
382 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
383 {
384         MonoImage *image;
385         MonoClass *klass = NULL, *eklass;
386         guint32 token, rank, idx;
387         guint8 *p = buf;
388         int reftype;
389
390         reftype = decode_value (p, &p);
391         if (reftype == 0) {
392                 *endbuf = p;
393                 return NULL;
394         }
395
396         switch (reftype) {
397         case MONO_AOT_TYPEREF_TYPEDEF_INDEX:
398                 idx = decode_value (p, &p);
399                 image = load_image (module, 0, TRUE);
400                 if (!image)
401                         return NULL;
402                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + idx);
403                 break;
404         case MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE:
405                 idx = decode_value (p, &p);
406                 image = load_image (module, decode_value (p, &p), TRUE);
407                 if (!image)
408                         return NULL;
409                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + idx);
410                 break;
411         case MONO_AOT_TYPEREF_TYPESPEC_TOKEN:
412                 token = decode_value (p, &p);
413                 image = module->assembly->image;
414                 if (!image)
415                         return NULL;
416                 klass = mono_class_get (image, token);
417                 break;
418         case MONO_AOT_TYPEREF_GINST: {
419                 MonoClass *gclass;
420                 MonoGenericContext ctx;
421                 MonoType *type;
422
423                 gclass = decode_klass_ref (module, p, &p);
424                 if (!gclass)
425                         return NULL;
426                 g_assert (gclass->generic_container);
427
428                 memset (&ctx, 0, sizeof (ctx));
429                 ctx.class_inst = decode_generic_inst (module, p, &p);
430                 if (!ctx.class_inst)
431                         return NULL;
432                 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
433                 klass = mono_class_from_mono_type (type);
434                 mono_metadata_free_type (type);
435                 break;
436         }
437         case MONO_AOT_TYPEREF_VAR: {
438                 MonoType *t;
439                 MonoGenericContainer *container = NULL;
440                 int type = decode_value (p, &p);
441                 int num = decode_value (p, &p);
442                 gboolean has_container = decode_value (p, &p);
443                 int serial = 0;
444
445                 if (has_container) {
446                         gboolean is_method = decode_value (p, &p);
447                         
448                         if (is_method) {
449                                 MonoMethod *method_def;
450                                 g_assert (type == MONO_TYPE_MVAR);
451                                 method_def = decode_resolve_method_ref (module, p, &p);
452                                 if (!method_def)
453                                         return NULL;
454
455                                 container = mono_method_get_generic_container (method_def);
456                         } else {
457                                 MonoClass *class_def;
458                                 g_assert (type == MONO_TYPE_VAR);
459                                 class_def = decode_klass_ref (module, p, &p);
460                                 if (!class_def)
461                                         return NULL;
462
463                                 container = class_def->generic_container;
464                         }
465                 } else {
466                         serial = decode_value (p, &p);
467                 }
468
469                 // FIXME: Memory management
470                 t = g_new0 (MonoType, 1);
471                 t->type = type;
472                 if (container) {
473                         t->data.generic_param = mono_generic_container_get_param (container, num);
474                         g_assert (serial == 0);
475                 } else {
476                         /* Anonymous */
477                         MonoGenericParam *par = (MonoGenericParam*)g_new0 (MonoGenericParamFull, 1);
478                         par->num = num;
479                         par->serial = serial;
480                         // FIXME:
481                         par->image = mono_defaults.corlib;
482                         t->data.generic_param = par;
483                 }
484
485                 // FIXME: Maybe use types directly to avoid
486                 // the overhead of creating MonoClass-es
487                 klass = mono_class_from_mono_type (t);
488
489                 g_free (t);
490                 break;
491         }
492         case MONO_AOT_TYPEREF_ARRAY:
493                 /* Array */
494                 rank = decode_value (p, &p);
495                 eklass = decode_klass_ref (module, p, &p);
496                 klass = mono_array_class_get (eklass, rank);
497                 break;
498         case MONO_AOT_TYPEREF_PTR: {
499                 MonoType *t;
500
501                 t = decode_type (module, p, &p);
502                 if (!t)
503                         return NULL;
504                 klass = mono_class_from_mono_type (t);
505                 g_free (t);
506                 break;
507         }
508         case MONO_AOT_TYPEREF_BLOB_INDEX: {
509                 guint32 offset = decode_value (p, &p);
510                 guint8 *p2;
511
512                 p2 = module->blob + offset;
513                 klass = decode_klass_ref (module, p2, &p2);
514                 break;
515         }
516         default:
517                 g_assert_not_reached ();
518         }
519         g_assert (klass);
520         //printf ("BLA: %s\n", mono_type_full_name (&klass->byval_arg));
521         *endbuf = p;
522         return klass;
523 }
524
525 static MonoClassField*
526 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
527 {
528         MonoClass *klass = decode_klass_ref (module, buf, &buf);
529         guint32 token;
530         guint8 *p = buf;
531
532         if (!klass)
533                 return NULL;
534
535         token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
536
537         *endbuf = p;
538
539         return mono_class_get_field (klass, token);
540 }
541
542 /*
543  * Parse a MonoType encoded by encode_type () in aot-compiler.c. Return malloc-ed
544  * memory.
545  */
546 static MonoType*
547 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
548 {
549         guint8 *p = buf;
550         MonoType *t;
551
552         t = g_malloc0 (sizeof (MonoType));
553
554         while (TRUE) {
555                 if (*p == MONO_TYPE_PINNED) {
556                         t->pinned = TRUE;
557                         ++p;
558                 } else if (*p == MONO_TYPE_BYREF) {
559                         t->byref = TRUE;
560                         ++p;
561                 } else {
562                         break;
563                 }
564         }
565
566         t->type = *p;
567         ++p;
568
569         switch (t->type) {
570         case MONO_TYPE_VOID:
571         case MONO_TYPE_BOOLEAN:
572         case MONO_TYPE_CHAR:
573         case MONO_TYPE_I1:
574         case MONO_TYPE_U1:
575         case MONO_TYPE_I2:
576         case MONO_TYPE_U2:
577         case MONO_TYPE_I4:
578         case MONO_TYPE_U4:
579         case MONO_TYPE_I8:
580         case MONO_TYPE_U8:
581         case MONO_TYPE_R4:
582         case MONO_TYPE_R8:
583         case MONO_TYPE_I:
584         case MONO_TYPE_U:
585         case MONO_TYPE_STRING:
586         case MONO_TYPE_OBJECT:
587         case MONO_TYPE_TYPEDBYREF:
588                 break;
589         case MONO_TYPE_VALUETYPE:
590         case MONO_TYPE_CLASS:
591                 t->data.klass = decode_klass_ref (module, p, &p);
592                 break;
593         case MONO_TYPE_SZARRAY:
594                 t->data.klass = decode_klass_ref (module, p, &p);
595
596                 if (!t->data.klass)
597                         return NULL;
598                 break;
599         case MONO_TYPE_PTR:
600                 t->data.type = decode_type (module, p, &p);
601                 break;
602         case MONO_TYPE_GENERICINST: {
603                 MonoClass *gclass;
604                 MonoGenericContext ctx;
605                 MonoType *type;
606                 MonoClass *klass;
607
608                 gclass = decode_klass_ref (module, p, &p);
609                 if (!gclass)
610                         return NULL;
611                 g_assert (gclass->generic_container);
612
613                 memset (&ctx, 0, sizeof (ctx));
614                 ctx.class_inst = decode_generic_inst (module, p, &p);
615                 if (!ctx.class_inst)
616                         return NULL;
617                 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
618                 klass = mono_class_from_mono_type (type);
619                 t->data.generic_class = klass->generic_class;
620                 break;
621         }
622         case MONO_TYPE_ARRAY: {
623                 MonoArrayType *array;
624                 int i;
625
626                 // FIXME: memory management
627                 array = g_new0 (MonoArrayType, 1);
628                 array->eklass = decode_klass_ref (module, p, &p);
629                 if (!array->eklass)
630                         return NULL;
631                 array->rank = decode_value (p, &p);
632                 array->numsizes = decode_value (p, &p);
633
634                 if (array->numsizes)
635                         array->sizes = g_malloc0 (sizeof (int) * array->numsizes);
636                 for (i = 0; i < array->numsizes; ++i)
637                         array->sizes [i] = decode_value (p, &p);
638
639                 array->numlobounds = decode_value (p, &p);
640                 if (array->numlobounds)
641                         array->lobounds = g_malloc0 (sizeof (int) * array->numlobounds);
642                 for (i = 0; i < array->numlobounds; ++i)
643                         array->lobounds [i] = decode_value (p, &p);
644                 t->data.array = array;
645                 break;
646         }
647         case MONO_TYPE_VAR:
648         case MONO_TYPE_MVAR: {
649                 MonoClass *klass = decode_klass_ref (module, p, &p);
650                 if (!klass)
651                         return NULL;
652                 t->data.generic_param = klass->byval_arg.data.generic_param;
653                 break;
654         }
655         default:
656                 g_assert_not_reached ();
657         }
658
659         *endbuf = p;
660
661         return t;
662 }
663
664 // FIXME: Error handling, memory management
665
666 static MonoMethodSignature*
667 decode_signature_with_target (MonoAotModule *module, MonoMethodSignature *target, guint8 *buf, guint8 **endbuf)
668 {
669         MonoMethodSignature *sig;
670         guint32 flags;
671         int i, param_count, call_conv, gen_param_count = 0;
672         guint8 *p = buf;
673         gboolean hasthis, explicit_this, has_gen_params;
674
675         flags = *p;
676         p ++;
677         has_gen_params = (flags & 0x10) != 0;
678         hasthis = (flags & 0x20) != 0;
679         explicit_this = (flags & 0x40) != 0;
680         call_conv = flags & 0x0F;
681
682         if (has_gen_params)
683                 gen_param_count = decode_value (p, &p);
684         param_count = decode_value (p, &p);
685         if (target && param_count != target->param_count)
686                 return NULL;
687         sig = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + param_count * sizeof (MonoType *));
688         sig->param_count = param_count;
689         sig->sentinelpos = -1;
690         sig->hasthis = hasthis;
691         sig->explicit_this = explicit_this;
692         sig->call_convention = call_conv;
693         sig->param_count = param_count;
694         sig->ret = decode_type (module, p, &p);
695         for (i = 0; i < param_count; ++i) {
696                 if (*p == MONO_TYPE_SENTINEL) {
697                         g_assert (sig->call_convention == MONO_CALL_VARARG);
698                         sig->sentinelpos = i;
699                         p ++;
700                 }
701                 sig->params [i] = decode_type (module, p, &p);
702         }
703
704         if (sig->call_convention == MONO_CALL_VARARG && sig->sentinelpos == -1)
705                 sig->sentinelpos = sig->param_count;
706
707         *endbuf = p;
708
709         return sig;
710 }
711
712 static MonoMethodSignature*
713 decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
714 {
715         return decode_signature_with_target (module, NULL, buf, endbuf);
716 }
717
718 static gboolean
719 sig_matches_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
720 {
721         MonoMethodSignature *sig;
722         gboolean res;
723         guint8 *p = buf;
724         
725         sig = decode_signature_with_target (module, mono_method_signature (target), p, &p);
726         res = sig && mono_metadata_signature_equal (mono_method_signature (target), sig);
727         g_free (sig);
728         *endbuf = p;
729         return res;
730 }
731
732 /* Stores information returned by decode_method_ref () */
733 typedef struct {
734         MonoImage *image;
735         guint32 token;
736         MonoMethod *method;
737         gboolean no_aot_trampoline;
738 } MethodRef;
739
740 /*
741  * decode_method_ref_with_target:
742  *
743  *   Decode a method reference, storing the image/token into a MethodRef structure.
744  * This avoids loading metadata for the method if the caller does not need it. If the method has
745  * no token, then it is loaded from metadata and ref->method is set to the method instance.
746  * If TARGET is non-NULL, abort decoding if it can be determined that the decoded method
747  *  couldn't resolve to TARGET, and return FALSE.
748  * There are some kinds of method references which only support a non-null TARGET.
749  * This means that its not possible to decode this into a method, only to check
750  * that the method reference matches a given method. This is normally not a problem
751  * as these wrappers only occur in the extra_methods table, where we already have
752  * a method we want to lookup.
753  */
754 static gboolean
755 decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf)
756 {
757         guint32 image_index, value;
758         MonoImage *image = NULL;
759         guint8 *p = buf;
760
761         memset (ref, 0, sizeof (MethodRef));
762
763         value = decode_value (p, &p);
764         image_index = value >> 24;
765
766         if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
767                 ref->no_aot_trampoline = TRUE;
768                 value = decode_value (p, &p);
769                 image_index = value >> 24;
770         }
771
772         if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) {
773                 if (target && target->wrapper_type)
774                         return FALSE;
775         }
776
777         if (image_index == MONO_AOT_METHODREF_WRAPPER) {
778                 guint32 wrapper_type;
779
780                 wrapper_type = decode_value (p, &p);
781
782                 if (target && target->wrapper_type != wrapper_type)
783                         return FALSE;
784
785                 /* Doesn't matter */
786                 image = mono_defaults.corlib;
787
788                 switch (wrapper_type) {
789 #ifndef DISABLE_REMOTING
790                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
791                         MonoMethod *m = decode_resolve_method_ref (module, p, &p);
792
793                         if (!m)
794                                 return FALSE;
795                         mono_class_init (m->klass);
796                         ref->method = mono_marshal_get_remoting_invoke_with_check (m);
797                         break;
798                 }
799                 case MONO_WRAPPER_PROXY_ISINST: {
800                         MonoClass *klass = decode_klass_ref (module, p, &p);
801                         if (!klass)
802                                 return FALSE;
803                         ref->method = mono_marshal_get_proxy_cancast (klass);
804                         break;
805                 }
806                 case MONO_WRAPPER_LDFLD:
807                 case MONO_WRAPPER_LDFLDA:
808                 case MONO_WRAPPER_STFLD:
809                 case MONO_WRAPPER_ISINST: {
810                         MonoClass *klass = decode_klass_ref (module, p, &p);
811                         if (!klass)
812                                 return FALSE;
813                         if (wrapper_type == MONO_WRAPPER_LDFLD)
814                                 ref->method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
815                         else if (wrapper_type == MONO_WRAPPER_LDFLDA)
816                                 ref->method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
817                         else if (wrapper_type == MONO_WRAPPER_STFLD)
818                                 ref->method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
819                         else if (wrapper_type == MONO_WRAPPER_ISINST)
820                                 ref->method = mono_marshal_get_isinst (klass);
821                         else
822                                 g_assert_not_reached ();
823                         break;
824                 }
825                 case MONO_WRAPPER_LDFLD_REMOTE:
826                         ref->method = mono_marshal_get_ldfld_remote_wrapper (NULL);
827                         break;
828                 case MONO_WRAPPER_STFLD_REMOTE:
829                         ref->method = mono_marshal_get_stfld_remote_wrapper (NULL);
830                         break;
831 #endif
832                 case MONO_WRAPPER_ALLOC: {
833                         int atype = decode_value (p, &p);
834
835                         ref->method = mono_gc_get_managed_allocator_by_type (atype);
836                         g_assert (ref->method);
837                         break;
838                 }
839                 case MONO_WRAPPER_WRITE_BARRIER:
840                         ref->method = mono_gc_get_write_barrier ();
841                         break;
842                 case MONO_WRAPPER_STELEMREF: {
843                         int subtype = decode_value (p, &p);
844
845                         if (subtype == WRAPPER_SUBTYPE_NONE) {
846                                 ref->method = mono_marshal_get_stelemref ();
847                         } else if (subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF) {
848                                 int kind;
849                                 WrapperInfo *info;
850                                 
851                                 kind = decode_value (p, &p);
852
853                                 /* Can't decode this */
854                                 if (!target)
855                                         return FALSE;
856                                 if (target->wrapper_type == MONO_WRAPPER_STELEMREF) {
857                                         info = mono_marshal_get_wrapper_info (target);
858
859                                         g_assert (info);
860                                         if (info->subtype == subtype && info->d.virtual_stelemref.kind == kind)
861                                                 ref->method = target;
862                                         else
863                                                 return FALSE;
864                                 } else {
865                                         return FALSE;
866                                 }
867                         } else {
868                                 g_assert_not_reached ();
869                         }
870                         break;
871                 }
872                 case MONO_WRAPPER_SYNCHRONIZED: {
873                         MonoMethod *m = decode_resolve_method_ref (module, p, &p);
874
875                         if (!m)
876                                 return FALSE;
877                         ref->method = mono_marshal_get_synchronized_wrapper (m);
878                         break;
879                 }
880                 case MONO_WRAPPER_UNKNOWN: {
881                         MonoMethodDesc *desc;
882                         MonoMethod *orig_method;
883                         int subtype = decode_value (p, &p);
884
885                         if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE || subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR) {
886                                 MonoClass *klass = decode_klass_ref (module, p, &p);
887                                 
888                                 if (!klass)
889                                         return FALSE;
890
891                                 if (!target)
892                                         return FALSE;
893                                 if (klass != target->klass)
894                                         return FALSE;
895
896                                 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE) {
897                                         if (strcmp (target->name, "PtrToStructure"))
898                                                 return FALSE;
899                                         ref->method = mono_marshal_get_ptr_to_struct (klass);
900                                 } else {
901                                         if (strcmp (target->name, "StructureToPtr"))
902                                                 return FALSE;
903                                         ref->method = mono_marshal_get_struct_to_ptr (klass);
904                                 }
905                         } else if (subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
906                                 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
907
908                                 if (!m)
909                                         return FALSE;
910                                 ref->method = mono_marshal_get_synchronized_inner_wrapper (m);
911                         } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN) {
912                                 ref->method = mono_marshal_get_gsharedvt_in_wrapper ();
913                         } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
914                                 ref->method = mono_marshal_get_gsharedvt_out_wrapper ();
915                         } else {
916                                 if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER)
917                                         desc = mono_method_desc_new ("Monitor:Enter", FALSE);
918                                 else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_EXIT)
919                                         desc = mono_method_desc_new ("Monitor:Exit", FALSE);
920                                 else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4)
921                                         desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
922                                 else
923                                         g_assert_not_reached ();
924                                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
925                                 g_assert (orig_method);
926                                 mono_method_desc_free (desc);
927                                 ref->method = mono_monitor_get_fast_path (orig_method);
928                         }
929                         break;
930                 }
931                 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
932                         int subtype = decode_value (p, &p);
933
934                         if (subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
935                                 int rank = decode_value (p, &p);
936                                 int elem_size = decode_value (p, &p);
937
938                                 ref->method = mono_marshal_get_array_address (rank, elem_size);
939                         } else if (subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
940                                 WrapperInfo *info;
941                                 MonoMethod *m;
942
943                                 m = decode_resolve_method_ref (module, p, &p);
944                                 if (!m)
945                                         return FALSE;
946
947                                 if (!target)
948                                         return FALSE;
949                                 g_assert (target->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED);
950
951                                 info = mono_marshal_get_wrapper_info (target);
952                                 if (info && info->subtype == subtype && info->d.string_ctor.method == m)
953                                         ref->method = target;
954                                 else
955                                         return FALSE;
956                         }
957                         break;
958                 }
959                 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
960                         MonoMethod *m;
961                         int subtype = decode_value (p, &p);
962                         char *name;
963
964                         if (subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
965                                 if (!target)
966                                         return FALSE;
967
968                                 name = (char*)p;
969                                 if (strcmp (target->name, name) != 0)
970                                         return FALSE;
971                                 ref->method = target;
972                         } else {
973                                 m = decode_resolve_method_ref (module, p, &p);
974
975                                 if (!m)
976                                         return FALSE;
977
978                                 /* This should only happen when looking for an extra method */
979                                 if (!target)
980                                         return FALSE;
981                                 if (mono_marshal_method_from_wrapper (target) == m)
982                                         ref->method = target;
983                                 else
984                                         return FALSE;
985                         }
986                         break;
987                 }
988                 case MONO_WRAPPER_CASTCLASS: {
989                         int subtype = decode_value (p, &p);
990
991                         if (subtype == WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE)
992                                 ref->method = mono_marshal_get_castclass_with_cache ();
993                         else if (subtype == WRAPPER_SUBTYPE_ISINST_WITH_CACHE)
994                                 ref->method = mono_marshal_get_isinst_with_cache ();
995                         else
996                                 g_assert_not_reached ();
997                         break;
998                 }
999                 case MONO_WRAPPER_RUNTIME_INVOKE: {
1000                         int subtype = decode_value (p, &p);
1001
1002                         if (!target)
1003                                 return FALSE;
1004
1005                         if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC) {
1006                                 if (strcmp (target->name, "runtime_invoke_dynamic") != 0)
1007                                         return FALSE;
1008                                 ref->method = target;
1009                         } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT) {
1010                                 /* Direct wrapper */
1011                                 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
1012
1013                                 if (!m)
1014                                         return FALSE;
1015                                 ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
1016                         } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL) {
1017                                 /* Virtual direct wrapper */
1018                                 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
1019
1020                                 if (!m)
1021                                         return FALSE;
1022                                 ref->method = mono_marshal_get_runtime_invoke (m, TRUE);
1023                         } else {
1024                                 if (sig_matches_target (module, target, p, &p))
1025                                         ref->method = target;
1026                                 else
1027                                         return FALSE;
1028                         }
1029                         break;
1030                 }
1031                 case MONO_WRAPPER_DELEGATE_INVOKE: {
1032                         gboolean is_inflated = decode_value (p, &p);
1033
1034                         if (is_inflated) {
1035                                 MonoClass *klass;
1036                                 MonoMethod *invoke, *wrapper;
1037
1038                                 klass = decode_klass_ref (module, p, &p);
1039                                 if (!klass)
1040                                         return FALSE;
1041                                 invoke = mono_get_delegate_invoke (klass);
1042                                 wrapper = mono_marshal_get_delegate_invoke (invoke, NULL);
1043                                 if (target && wrapper != target)
1044                                         return FALSE;
1045                                 ref->method = wrapper;
1046                                 break;
1047                         } else {
1048                                 /* Fall through */
1049                         }
1050                 }
1051                 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
1052                 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
1053                         /*
1054                          * These wrappers are associated with a signature, not with a method.
1055                          * Since we can't decode them into methods, they need a target method.
1056                          */
1057                         if (!target)
1058                                 return FALSE;
1059
1060                         if (sig_matches_target (module, target, p, &p))
1061                                 ref->method = target;
1062                         else
1063                                 return FALSE;
1064                         break;
1065                 }
1066                 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
1067                         MonoMethod *m;
1068                         MonoClass *klass;
1069
1070                         m = decode_resolve_method_ref (module, p, &p);
1071                         if (!m)
1072                                 return FALSE;
1073                         klass = decode_klass_ref (module, p, &p);
1074                         if (!klass)
1075                                 return FALSE;
1076                         ref->method = mono_marshal_get_managed_wrapper (m, klass, 0);
1077                         break;
1078                 }
1079                 default:
1080                         g_assert_not_reached ();
1081                 }
1082         } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
1083                 image_index = decode_value (p, &p);
1084                 ref->token = decode_value (p, &p);
1085
1086                 image = load_image (module, image_index, TRUE);
1087                 if (!image)
1088                         return FALSE;
1089         } else if (image_index == MONO_AOT_METHODREF_GINST) {
1090                 MonoClass *klass;
1091                 MonoGenericContext ctx;
1092
1093                 /* 
1094                  * These methods do not have a token which resolves them, so we 
1095                  * resolve them immediately.
1096                  */
1097                 klass = decode_klass_ref (module, p, &p);
1098                 if (!klass)
1099                         return FALSE;
1100
1101                 if (target && target->klass != klass)
1102                         return FALSE;
1103
1104                 image_index = decode_value (p, &p);
1105                 ref->token = decode_value (p, &p);
1106
1107                 image = load_image (module, image_index, TRUE);
1108                 if (!image)
1109                         return FALSE;
1110
1111                 ref->method = mono_get_method_full (image, ref->token, NULL, NULL);
1112                 if (!ref->method)
1113                         return FALSE;
1114
1115                 memset (&ctx, 0, sizeof (ctx));
1116
1117                 if (FALSE && klass->generic_class) {
1118                         ctx.class_inst = klass->generic_class->context.class_inst;
1119                         ctx.method_inst = NULL;
1120  
1121                         ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
1122                 }                       
1123
1124                 memset (&ctx, 0, sizeof (ctx));
1125
1126                 if (!decode_generic_context (module, &ctx, p, &p))
1127                         return FALSE;
1128
1129                 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
1130         } else if (image_index == MONO_AOT_METHODREF_ARRAY) {
1131                 MonoClass *klass;
1132                 int method_type;
1133
1134                 klass = decode_klass_ref (module, p, &p);
1135                 if (!klass)
1136                         return FALSE;
1137                 method_type = decode_value (p, &p);
1138                 switch (method_type) {
1139                 case 0:
1140                         ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank);
1141                         break;
1142                 case 1:
1143                         ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank * 2);
1144                         break;
1145                 case 2:
1146                         ref->method = mono_class_get_method_from_name (klass, "Get", -1);
1147                         break;
1148                 case 3:
1149                         ref->method = mono_class_get_method_from_name (klass, "Address", -1);
1150                         break;
1151                 case 4:
1152                         ref->method = mono_class_get_method_from_name (klass, "Set", -1);
1153                         break;
1154                 default:
1155                         g_assert_not_reached ();
1156                 }
1157         } else {
1158                 if (image_index == MONO_AOT_METHODREF_LARGE_IMAGE_INDEX) {
1159                         image_index = decode_value (p, &p);
1160                         value = decode_value (p, &p);
1161                 }
1162
1163                 ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1164
1165                 image = load_image (module, image_index, TRUE);
1166                 if (!image)
1167                         return FALSE;
1168         }
1169
1170         *endbuf = p;
1171
1172         ref->image = image;
1173
1174         return TRUE;
1175 }
1176
1177 static gboolean
1178 decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf)
1179 {
1180         return decode_method_ref_with_target (module, ref, NULL, buf, endbuf);
1181 }
1182
1183 /*
1184  * decode_resolve_method_ref_with_target:
1185  *
1186  *   Similar to decode_method_ref, but resolve and return the method itself.
1187  */
1188 static MonoMethod*
1189 decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
1190 {
1191         MethodRef ref;
1192         gboolean res;
1193
1194         res = decode_method_ref_with_target (module, &ref, target, buf, endbuf);
1195         if (!res)
1196                 return NULL;
1197         if (ref.method)
1198                 return ref.method;
1199         if (!ref.image)
1200                 return NULL;
1201         return mono_get_method (ref.image, ref.token, NULL);
1202 }
1203
1204 static MonoMethod*
1205 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
1206 {
1207         return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf);
1208 }
1209
1210 static void
1211 create_cache_structure (void)
1212 {
1213         const char *home;
1214         char *tmp;
1215         int err;
1216
1217         home = g_get_home_dir ();
1218         if (!home)
1219                 return;
1220
1221         tmp = g_build_filename (home, ".mono", NULL);
1222         if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
1223                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
1224 #ifdef HOST_WIN32
1225                 err = mkdir (tmp);
1226 #else
1227                 err = mkdir (tmp, 0777);
1228 #endif
1229                 if (err) {
1230                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
1231                         g_free (tmp);
1232                         return;
1233                 }
1234         }
1235         g_free (tmp);
1236         tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
1237         if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
1238                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
1239 #ifdef HOST_WIN32
1240                 err = mkdir (tmp);
1241 #else
1242                 err = mkdir (tmp, 0777);
1243 #endif
1244                 if (err) {
1245                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
1246                         g_free (tmp);
1247                         return;
1248                 }
1249         }
1250         g_free (tmp);
1251 }
1252
1253 /*
1254  * load_aot_module_from_cache:
1255  *
1256  *  Experimental code to AOT compile loaded assemblies on demand. 
1257  *
1258  * FIXME: 
1259  * - Add environment variable MONO_AOT_CACHE_OPTIONS
1260  * - Add options for controlling the cache size
1261  * - Handle full cache by deleting old assemblies lru style
1262  * - Add options for excluding assemblies during development
1263  * - Maybe add a threshold after an assembly is AOT compiled
1264  * - invoking a new mono process is a security risk
1265  * - recompile the AOT module if one of its dependencies changes
1266  */
1267 static MonoDl*
1268 load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
1269 {
1270         char *fname, *cmd, *tmp2, *aot_options;
1271         const char *home;
1272         MonoDl *module;
1273         gboolean res;
1274         gchar *out, *err;
1275         gint exit_status;
1276
1277         *aot_name = NULL;
1278
1279         if (assembly->image->dynamic)
1280                 return NULL;
1281
1282         create_cache_structure ();
1283
1284         home = g_get_home_dir ();
1285
1286         tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
1287         fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
1288         *aot_name = fname;
1289         g_free (tmp2);
1290
1291         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
1292         module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1293
1294         if (!module) {
1295                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");
1296
1297                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);
1298
1299                 aot_options = g_strdup_printf ("outfile=%s", fname);
1300
1301                 if (spawn_compiler) {
1302                         /* FIXME: security */
1303                         /* FIXME: Has to pass the assembly loading path to the child process */
1304                         cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name);
1305
1306                         res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
1307
1308 #if !defined(HOST_WIN32) && !defined(__ppc__) && !defined(__ppc64__) && !defined(__powerpc__)
1309                         if (res) {
1310                                 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
1311                                         mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err);
1312                                 else
1313                                         mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
1314                                 g_free (out);
1315                                 g_free (err);
1316                         }
1317 #endif
1318                         g_free (cmd);
1319                 } else {
1320                         res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
1321                         if (!res) {
1322                                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
1323                         } else {
1324                                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
1325                         }
1326                 }
1327
1328                 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1329
1330                 g_free (aot_options);
1331         }
1332
1333         return module;
1334 }
1335
1336 static void
1337 find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
1338 {
1339         if (globals) {
1340                 int global_index;
1341                 guint16 *table, *entry;
1342                 guint16 table_size;
1343                 guint32 hash;           
1344                 char *symbol = (char*)name;
1345
1346 #ifdef TARGET_MACH
1347                 symbol = g_strdup_printf ("_%s", name);
1348 #endif
1349
1350                 /* The first entry points to the hash */
1351                 table = globals [0];
1352                 globals ++;
1353
1354                 table_size = table [0];
1355                 table ++;
1356
1357                 hash = mono_metadata_str_hash (symbol) % table_size;
1358
1359                 entry = &table [hash * 2];
1360
1361                 /* Search the hash for the index into the globals table */
1362                 global_index = -1;
1363                 while (entry [0] != 0) {
1364                         guint32 index = entry [0] - 1;
1365                         guint32 next = entry [1];
1366
1367                         //printf ("X: %s %s\n", (char*)globals [index * 2], name);
1368
1369                         if (!strcmp (globals [index * 2], symbol)) {
1370                                 global_index = index;
1371                                 break;
1372                         }
1373
1374                         if (next != 0) {
1375                                 entry = &table [next * 2];
1376                         } else {
1377                                 break;
1378                         }
1379                 }
1380
1381                 if (global_index != -1)
1382                         *value = globals [global_index * 2 + 1];
1383                 else
1384                         *value = NULL;
1385
1386                 if (symbol != name)
1387                         g_free (symbol);
1388         } else {
1389                 char *err = mono_dl_symbol (module, name, value);
1390
1391                 if (err)
1392                         g_free (err);
1393         }
1394 }
1395
1396 static gboolean
1397 check_usable (MonoAssembly *assembly, MonoAotFileInfo *info, char **out_msg)
1398 {
1399         char *build_info;
1400         char *msg = NULL;
1401         gboolean usable = TRUE;
1402         gboolean full_aot;
1403         guint8 *blob;
1404         guint32 excluded_cpu_optimizations;
1405
1406         if (strcmp (assembly->image->guid, info->assembly_guid)) {
1407                 msg = g_strdup_printf ("doesn't match assembly");
1408                 usable = FALSE;
1409         }
1410
1411         build_info = mono_get_runtime_build_info ();
1412         if (strlen (info->runtime_version) > 0 && strcmp (info->runtime_version, build_info)) {
1413                 msg = g_strdup_printf ("compiled against runtime version '%s' while this runtime has version '%s'", info->runtime_version, build_info);
1414                 usable = FALSE;
1415         }
1416         g_free (build_info);
1417
1418         full_aot = info->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1419
1420         if (mono_aot_only && !full_aot) {
1421                 msg = g_strdup_printf ("not compiled with --aot=full");
1422                 usable = FALSE;
1423         }
1424         if (!mono_aot_only && full_aot) {
1425                 msg = g_strdup_printf ("compiled with --aot=full");
1426                 usable = FALSE;
1427         }
1428 #ifdef TARGET_ARM
1429         /* mono_arch_find_imt_method () requires this */
1430         if ((info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) {
1431                 msg = g_strdup_printf ("compiled against LLVM");
1432                 usable = FALSE;
1433         }
1434         if (!(info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && mono_use_llvm) {
1435                 msg = g_strdup_printf ("not compiled against LLVM");
1436                 usable = FALSE;
1437         }
1438 #endif
1439         if (mini_get_debug_options ()->mdb_optimizations && !(info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot) {
1440                 msg = g_strdup_printf ("not compiled for debugging");
1441                 usable = FALSE;
1442         }
1443
1444         mono_arch_cpu_optimizations (&excluded_cpu_optimizations);
1445         if (info->opts & excluded_cpu_optimizations) {
1446                 msg = g_strdup_printf ("compiled with unsupported CPU optimizations");
1447                 usable = FALSE;
1448         }
1449
1450         if (!mono_aot_only && (info->simd_opts & ~mono_arch_cpu_enumerate_simd_versions ())) {
1451                 msg = g_strdup_printf ("compiled with unsupported SIMD extensions");
1452                 usable = FALSE;
1453         }
1454
1455         blob = info->blob;
1456
1457         if (info->gc_name_index != -1) {
1458                 char *gc_name = (char*)&blob [info->gc_name_index];
1459                 const char *current_gc_name = mono_gc_get_gc_name ();
1460
1461                 if (strcmp (current_gc_name, gc_name) != 0) {
1462                         msg = g_strdup_printf ("compiled against GC %s, while the current runtime uses GC %s.\n", gc_name, current_gc_name);
1463                         usable = FALSE;
1464                 }
1465         }
1466
1467         *out_msg = msg;
1468         return usable;
1469 }
1470
1471 static void
1472 load_aot_module (MonoAssembly *assembly, gpointer user_data)
1473 {
1474         char *aot_name;
1475         MonoAotModule *amodule;
1476         MonoDl *sofile;
1477         gboolean usable = TRUE;
1478         char *version_symbol = NULL;
1479         char *msg = NULL;
1480         gpointer *globals = NULL;
1481         MonoAotFileInfo *info = NULL;
1482         int i, version;
1483         guint8 *blob;
1484         gboolean do_load_image = TRUE;
1485
1486         if (mono_compile_aot)
1487                 return;
1488
1489         if (assembly->image->aot_module)
1490                 /* 
1491                  * Already loaded. This can happen because the assembly loading code might invoke
1492                  * the assembly load hooks multiple times for the same assembly.
1493                  */
1494                 return;
1495
1496         if (assembly->image->dynamic)
1497                 return;
1498
1499         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
1500                 return;
1501
1502         mono_aot_lock ();
1503         if (static_aot_modules)
1504                 info = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
1505         else
1506                 info = NULL;
1507         mono_aot_unlock ();
1508
1509         if (info) {
1510                 /* Statically linked AOT module */
1511                 sofile = NULL;
1512                 aot_name = g_strdup_printf ("%s", assembly->aname.name);
1513                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
1514                 globals = info->globals;
1515         } else {
1516                 if (use_aot_cache)
1517                         sofile = load_aot_module_from_cache (assembly, &aot_name);
1518                 else {
1519                         char *err;
1520                         aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
1521
1522                         sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
1523
1524                         if (!sofile) {
1525                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err);
1526                                 g_free (err);
1527                         }
1528                 }
1529         }
1530
1531         if (!sofile && !globals) {
1532                 if (mono_aot_only && assembly->image->tables [MONO_TABLE_METHOD].rows) {
1533                         fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
1534                         exit (1);
1535                 }
1536                 g_free (aot_name);
1537                 return;
1538         }
1539
1540         if (!info) {
1541                 find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
1542                 find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
1543         }
1544
1545         if (version_symbol) {
1546                 /* Old file format */
1547                 version = atoi (version_symbol);
1548         } else {
1549                 g_assert (info);
1550                 version = info->version;
1551         }
1552
1553         if (version != MONO_AOT_FILE_VERSION) {
1554                 msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
1555                 usable = FALSE;
1556         } else {
1557                 usable = check_usable (assembly, info, &msg);
1558         }
1559
1560         if (!usable) {
1561                 if (mono_aot_only) {
1562                         fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode: %s.\n", aot_name, msg);
1563                         exit (1);
1564                 } else {
1565                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable: %s.\n", aot_name, msg);
1566                 }
1567                 g_free (msg);
1568                 g_free (aot_name);
1569                 if (sofile)
1570                         mono_dl_close (sofile);
1571                 assembly->image->aot_module = NULL;
1572                 return;
1573         }
1574
1575         /* Sanity check */
1576         g_assert (info->double_align == __alignof__ (double));
1577         g_assert (info->long_align == __alignof__ (gint64));
1578
1579         blob = info->blob;
1580
1581         amodule = g_new0 (MonoAotModule, 1);
1582         amodule->aot_name = aot_name;
1583         amodule->assembly = assembly;
1584
1585         memcpy (&amodule->info, info, sizeof (*info));
1586
1587         amodule->got = amodule->info.got;
1588         amodule->got [0] = assembly->image;
1589         amodule->globals = globals;
1590         amodule->sofile = sofile;
1591         amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
1592         amodule->blob = blob;
1593
1594         /* Read image table */
1595         {
1596                 guint32 table_len, i;
1597                 char *table = NULL;
1598
1599                 table = info->image_table;
1600                 g_assert (table);
1601
1602                 table_len = *(guint32*)table;
1603                 table += sizeof (guint32);
1604                 amodule->image_table = g_new0 (MonoImage*, table_len);
1605                 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
1606                 amodule->image_guids = g_new0 (char*, table_len);
1607                 amodule->image_table_len = table_len;
1608                 for (i = 0; i < table_len; ++i) {
1609                         MonoAssemblyName *aname = &(amodule->image_names [i]);
1610
1611                         aname->name = g_strdup (table);
1612                         table += strlen (table) + 1;
1613                         amodule->image_guids [i] = g_strdup (table);
1614                         table += strlen (table) + 1;
1615                         if (table [0] != 0)
1616                                 aname->culture = g_strdup (table);
1617                         table += strlen (table) + 1;
1618                         memcpy (aname->public_key_token, table, strlen (table) + 1);
1619                         table += strlen (table) + 1;                    
1620
1621                         table = ALIGN_PTR_TO (table, 8);
1622                         aname->flags = *(guint32*)table;
1623                         table += 4;
1624                         aname->major = *(guint32*)table;
1625                         table += 4;
1626                         aname->minor = *(guint32*)table;
1627                         table += 4;
1628                         aname->build = *(guint32*)table;
1629                         table += 4;
1630                         aname->revision = *(guint32*)table;
1631                         table += 4;
1632                 }
1633         }
1634
1635         amodule->code_offsets = info->code_offsets;
1636 #ifdef MONOTOUCH
1637         amodule->method_addresses = info->method_addresses;
1638 #endif
1639         amodule->code = info->methods;
1640 #ifdef TARGET_ARM
1641         /* Mask out thumb interop bit */
1642         amodule->code = (void*)((mgreg_t)amodule->code & ~1);
1643 #endif
1644         amodule->code_end = info->methods_end;
1645         amodule->method_info_offsets = info->method_info_offsets;
1646         amodule->ex_info_offsets = info->ex_info_offsets;
1647         amodule->class_info_offsets = info->class_info_offsets;
1648         amodule->class_name_table = info->class_name_table;
1649         amodule->extra_method_table = info->extra_method_table;
1650         amodule->extra_method_info_offsets = info->extra_method_info_offsets;
1651         amodule->unbox_trampolines = info->unbox_trampolines;
1652         amodule->unbox_trampolines_end = info->unbox_trampolines_end;
1653         amodule->got_info_offsets = info->got_info_offsets;
1654         amodule->unwind_info = info->unwind_info;
1655         amodule->mem_end = info->mem_end;
1656         amodule->mem_begin = amodule->code;
1657         amodule->plt = info->plt;
1658         amodule->plt_end = info->plt_end;
1659         amodule->mono_eh_frame = info->mono_eh_frame;
1660         amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = info->specific_trampolines;
1661         amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = info->static_rgctx_trampolines;
1662         amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK] = info->imt_thunks;
1663         amodule->trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = info->gsharedvt_arg_trampolines;
1664         amodule->thumb_end = info->thumb_end;
1665
1666 #ifdef MONOTOUCH
1667         if (info->flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES) {
1668                 /* Compute code_offsets from the method addresses */
1669                 amodule->code_offsets = g_malloc0 (amodule->info.nmethods * sizeof (gint32));
1670                 for (i = 0; i < amodule->info.nmethods; ++i) {
1671                         if (!amodule->method_addresses [i])
1672                                 amodule->code_offsets [i] = 0xffffffff;
1673                         else
1674                                 amodule->code_offsets [i] = (char*)amodule->method_addresses [i] - (char*)amodule->code;
1675                 }
1676         }
1677 #endif
1678
1679         if (make_unreadable) {
1680 #ifndef TARGET_WIN32
1681                 guint8 *addr;
1682                 guint8 *page_start, *page_end;
1683                 int err, len;
1684
1685                 addr = amodule->mem_begin;
1686                 len = amodule->mem_end - amodule->mem_begin;
1687
1688                 /* Round down in both directions to avoid modifying data which is not ours */
1689                 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
1690                 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
1691                 if (page_end > page_start) {
1692                         err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
1693                         g_assert (err == 0);
1694                 }
1695 #endif
1696         }
1697
1698         mono_aot_lock ();
1699
1700         aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
1701         aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);
1702
1703         g_hash_table_insert (aot_modules, assembly, amodule);
1704         mono_aot_unlock ();
1705
1706         mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);
1707
1708         assembly->image->aot_module = amodule;
1709
1710         if (mono_aot_only) {
1711                 char *code;
1712                 find_symbol (amodule->sofile, amodule->globals, "specific_trampolines_page", (gpointer *)&code);
1713                 amodule->use_page_trampolines = code != NULL;
1714                 /*g_warning ("using page trampolines: %d", amodule->use_page_trampolines);*/
1715                 if (mono_defaults.corlib) {
1716                         /* The second got slot contains the mscorlib got addr */
1717                         MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1718
1719                         amodule->got [1] = mscorlib_amodule->got;
1720                 } else {
1721                         amodule->got [1] = amodule->got;
1722                 }
1723         }
1724
1725         if (mono_gc_is_moving ()) {
1726                 MonoJumpInfo ji;
1727
1728                 memset (&ji, 0, sizeof (ji));
1729                 ji.type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
1730
1731                 amodule->got [2] = mono_resolve_patch_target (NULL, mono_get_root_domain (), NULL, &ji, FALSE);
1732         }
1733
1734         /*
1735          * Since we store methoddef and classdef tokens when referring to methods/classes in
1736          * referenced assemblies, we depend on the exact versions of the referenced assemblies.
1737          * MS calls this 'hard binding'. This means we have to load all referenced assemblies
1738          * non-lazily, since we can't handle out-of-date errors later.
1739          * The cached class info also depends on the exact assemblies.
1740          */
1741 #if defined(__native_client__)
1742         /* TODO: Don't 'load_image' on mscorlib due to a */
1743         /* recursive loading problem.  This should be    */
1744         /* removed if mscorlib is loaded from disk.      */
1745         if (strncmp(assembly->aname.name, "mscorlib", 8)) {
1746                 do_load_image = TRUE;
1747         } else {
1748                 do_load_image = FALSE;
1749         }
1750 #endif
1751         if (do_load_image) {
1752                 for (i = 0; i < amodule->image_table_len; ++i)
1753                         load_image (amodule, i, FALSE);
1754         }
1755
1756         if (amodule->out_of_date) {
1757                 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);
1758                 if (mono_aot_only) {
1759                         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);
1760                         exit (1);
1761                 }
1762         }
1763         else
1764                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
1765 }
1766
1767 /*
1768  * mono_aot_register_globals:
1769  *
1770  *   This is called by the ctor function in AOT images compiled with the
1771  * 'no-dlsym' option.
1772  */
1773 void
1774 mono_aot_register_globals (gpointer *globals)
1775 {
1776         g_assert_not_reached ();
1777 }
1778
1779 /*
1780  * mono_aot_register_module:
1781  *
1782  *   This should be called by embedding code to register AOT modules statically linked
1783  * into the executable. AOT_INFO should be the value of the 
1784  * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
1785  */
1786 void
1787 mono_aot_register_module (gpointer *aot_info)
1788 {
1789         gpointer *globals;
1790         char *aname;
1791         MonoAotFileInfo *info = (gpointer)aot_info;
1792
1793         g_assert (info->version == MONO_AOT_FILE_VERSION);
1794
1795         globals = info->globals;
1796         g_assert (globals);
1797
1798         aname = info->assembly_name;
1799
1800         /* This could be called before startup */
1801         if (aot_modules)
1802                 mono_aot_lock ();
1803
1804         if (!static_aot_modules)
1805                 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
1806
1807         g_hash_table_insert (static_aot_modules, aname, info);
1808
1809         if (aot_modules)
1810                 mono_aot_unlock ();
1811 }
1812
1813 void
1814 mono_aot_init (void)
1815 {
1816         InitializeCriticalSection (&aot_mutex);
1817         InitializeCriticalSection (&aot_page_mutex);
1818         aot_modules = g_hash_table_new (NULL, NULL);
1819
1820         mono_install_assembly_load_hook (load_aot_module, NULL);
1821
1822         if (g_getenv ("MONO_LASTAOT"))
1823                 mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
1824         if (g_getenv ("MONO_AOT_CACHE"))
1825                 use_aot_cache = TRUE;
1826 }
1827
1828 void
1829 mono_aot_cleanup (void)
1830 {
1831         if (aot_jit_icall_hash)
1832                 g_hash_table_destroy (aot_jit_icall_hash);
1833         if (aot_modules)
1834                 g_hash_table_destroy (aot_modules);
1835 }
1836
1837 static gboolean
1838 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
1839 {
1840         guint32 flags;
1841         MethodRef ref;
1842         gboolean res;
1843
1844         info->vtable_size = decode_value (buf, &buf);
1845         if (info->vtable_size == -1)
1846                 /* Generic type */
1847                 return FALSE;
1848         flags = decode_value (buf, &buf);
1849         info->ghcimpl = (flags >> 0) & 0x1;
1850         info->has_finalize = (flags >> 1) & 0x1;
1851         info->has_cctor = (flags >> 2) & 0x1;
1852         info->has_nested_classes = (flags >> 3) & 0x1;
1853         info->blittable = (flags >> 4) & 0x1;
1854         info->has_references = (flags >> 5) & 0x1;
1855         info->has_static_refs = (flags >> 6) & 0x1;
1856         info->no_special_static_fields = (flags >> 7) & 0x1;
1857         info->is_generic_container = (flags >> 8) & 0x1;
1858
1859         if (info->has_cctor) {
1860                 res = decode_method_ref (module, &ref, buf, &buf);
1861                 if (!res)
1862                         return FALSE;
1863                 info->cctor_token = ref.token;
1864         }
1865         if (info->has_finalize) {
1866                 res = decode_method_ref (module, &ref, buf, &buf);
1867                 if (!res)
1868                         return FALSE;
1869                 info->finalize_image = ref.image;
1870                 info->finalize_token = ref.token;
1871         }
1872
1873         info->instance_size = decode_value (buf, &buf);
1874         info->class_size = decode_value (buf, &buf);
1875         info->packing_size = decode_value (buf, &buf);
1876         info->min_align = decode_value (buf, &buf);
1877
1878         *endbuf = buf;
1879
1880         return TRUE;
1881 }       
1882
1883 gpointer
1884 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
1885 {
1886         int i;
1887         MonoClass *klass = vtable->klass;
1888         MonoAotModule *amodule = klass->image->aot_module;
1889         guint8 *info, *p;
1890         MonoCachedClassInfo class_info;
1891         gboolean err;
1892         MethodRef ref;
1893         gboolean res;
1894
1895         if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !amodule)
1896                 return NULL;
1897
1898         info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1899         p = info;
1900
1901         err = decode_cached_class_info (amodule, &class_info, p, &p);
1902         if (!err)
1903                 return NULL;
1904
1905         for (i = 0; i < slot; ++i)
1906                 decode_method_ref (amodule, &ref, p, &p);
1907
1908         res = decode_method_ref (amodule, &ref, p, &p);
1909         if (!res)
1910                 return NULL;
1911         if (ref.no_aot_trampoline)
1912                 return NULL;
1913
1914         if (mono_metadata_token_index (ref.token) == 0 || mono_metadata_token_table (ref.token) != MONO_TABLE_METHOD)
1915                 return NULL;
1916
1917         return mono_aot_get_method_from_token (domain, ref.image, ref.token);
1918 }
1919
1920 gboolean
1921 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
1922 {
1923         MonoAotModule *amodule = klass->image->aot_module;
1924         guint8 *p;
1925         gboolean err;
1926
1927         if (klass->rank || !amodule)
1928                 return FALSE;
1929
1930         p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1931
1932         err = decode_cached_class_info (amodule, res, p, &p);
1933         if (!err)
1934                 return FALSE;
1935
1936         return TRUE;
1937 }
1938
1939 /**
1940  * mono_aot_get_class_from_name:
1941  *
1942  *  Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
1943  * using a cache stored in the AOT file.
1944  * Stores the resulting class in *KLASS if found, stores NULL otherwise.
1945  *
1946  * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was 
1947  * found.
1948  */
1949 gboolean
1950 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
1951 {
1952         MonoAotModule *amodule = image->aot_module;
1953         guint16 *table, *entry;
1954         guint16 table_size;
1955         guint32 hash;
1956         char full_name_buf [1024];
1957         char *full_name;
1958         const char *name2, *name_space2;
1959         MonoTableInfo  *t;
1960         guint32 cols [MONO_TYPEDEF_SIZE];
1961         GHashTable *nspace_table;
1962
1963         if (!amodule || !amodule->class_name_table)
1964                 return FALSE;
1965
1966         mono_aot_lock ();
1967
1968         *klass = NULL;
1969
1970         /* First look in the cache */
1971         if (!amodule->name_cache)
1972                 amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
1973         nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
1974         if (nspace_table) {
1975                 *klass = g_hash_table_lookup (nspace_table, name);
1976                 if (*klass) {
1977                         mono_aot_unlock ();
1978                         return TRUE;
1979                 }
1980         }
1981
1982         table_size = amodule->class_name_table [0];
1983         table = amodule->class_name_table + 1;
1984
1985         if (name_space [0] == '\0')
1986                 full_name = g_strdup_printf ("%s", name);
1987         else {
1988                 if (strlen (name_space) + strlen (name) < 1000) {
1989                         sprintf (full_name_buf, "%s.%s", name_space, name);
1990                         full_name = full_name_buf;
1991                 } else {
1992                         full_name = g_strdup_printf ("%s.%s", name_space, name);
1993                 }
1994         }
1995         hash = mono_metadata_str_hash (full_name) % table_size;
1996         if (full_name != full_name_buf)
1997                 g_free (full_name);
1998
1999         entry = &table [hash * 2];
2000
2001         if (entry [0] != 0) {
2002                 t = &image->tables [MONO_TABLE_TYPEDEF];
2003
2004                 while (TRUE) {
2005                         guint32 index = entry [0];
2006                         guint32 next = entry [1];
2007                         guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
2008
2009                         name_table_accesses ++;
2010
2011                         mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
2012
2013                         name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2014                         name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2015
2016                         if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
2017                                 mono_aot_unlock ();
2018                                 *klass = mono_class_get (image, token);
2019
2020                                 /* Add to cache */
2021                                 if (*klass) {
2022                                         mono_aot_lock ();
2023                                         nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
2024                                         if (!nspace_table) {
2025                                                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
2026                                                 g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
2027                                         }
2028                                         g_hash_table_insert (nspace_table, (char*)name2, *klass);
2029                                         mono_aot_unlock ();
2030                                 }
2031                                 return TRUE;
2032                         }
2033
2034                         if (next != 0) {
2035                                 entry = &table [next * 2];
2036                         } else {
2037                                 break;
2038                         }
2039                 }
2040         }
2041
2042         mono_aot_unlock ();
2043         
2044         return TRUE;
2045 }
2046
2047 /*
2048  * decode_mono_eh_frame:
2049  *
2050  *   Decode the EH information emitted by our modified LLVM compiler and construct a
2051  * MonoJitInfo structure from it.
2052  * LOCKING: Acquires the domain lock.
2053  */
2054 static MonoJitInfo*
2055 decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoDomain *domain, 
2056                                                    MonoMethod *method, guint8 *code, 
2057                                                    MonoJitExceptionInfo *clauses, int num_clauses,
2058                                                    int extra_size, GSList **nesting,
2059                                                    int *this_reg, int *this_offset)
2060 {
2061         guint8 *p;
2062         guint8 *fde, *cie, *code_start, *code_end;
2063         int version, fde_count;
2064         gint32 *table;
2065         int i, j, pos, left, right, offset, offset1, offset2, code_len, func_encoding;
2066         MonoJitExceptionInfo *ei;
2067         guint32 fde_len, ei_len, nested_len, nindex;
2068         gpointer *type_info;
2069         MonoJitInfo *jinfo;
2070         MonoLLVMFDEInfo info;
2071
2072         g_assert (amodule->mono_eh_frame);
2073
2074         p = amodule->mono_eh_frame;
2075
2076         /* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
2077
2078         /* Header */
2079         version = *p;
2080         g_assert (version == 1 || version == 2);
2081         p ++;
2082         if (version == 2) {
2083                 func_encoding = *p;
2084                 p ++;
2085         } else {
2086                 func_encoding = DW_EH_PE_pcrel;
2087         }
2088         p = ALIGN_PTR_TO (p, 4);
2089
2090         fde_count = *(guint32*)p;
2091         p += 4;
2092         table = (gint32*)p;
2093
2094         /* There is +1 entry in the table */
2095         cie = p + ((fde_count + 1) * 8);
2096
2097         /* Binary search in the table to find the entry for code */
2098         offset = code - amodule->mono_eh_frame;
2099
2100         left = 0;
2101         right = fde_count;
2102         while (TRUE) {
2103                 pos = (left + right) / 2;
2104
2105                 offset1 = table [(pos * 2)];
2106                 if (pos + 1 == fde_count) {
2107                         /* FIXME: */
2108                         offset2 = amodule->code_end - amodule->code;
2109                 } else {
2110                         /* Encoded as DW_EH_PE_pcrel, but relative to mono_eh_frame */
2111                         offset2 = table [(pos + 1) * 2];
2112                 }
2113
2114                 if (func_encoding == DW_EH_PE_absptr) {
2115                         /*
2116                          * Encoded as DW_EH_PE_absptr, because the ios linker can move functions inside object files to make thumb work,
2117                          * so the offsets between two symbols in the text segment are not assembler constant.
2118                          */
2119                         g_assert (sizeof(gpointer) == 4);
2120                         offset1 -= (gint32)(gsize)amodule->mono_eh_frame;
2121                         offset2 -= (gint32)(gsize)amodule->mono_eh_frame;
2122                 }
2123
2124                 if (offset < offset1)
2125                         right = pos;
2126                 else if (offset >= offset2)
2127                         left = pos + 1;
2128                 else
2129                         break;
2130         }
2131
2132         if (func_encoding == DW_EH_PE_absptr) {
2133                 code_start = (gpointer)(gsize)table [(pos * 2)];
2134                 code_end = (gpointer)(gsize)table [(pos * 2) + 2];
2135         } else {
2136                 code_start = amodule->mono_eh_frame + table [(pos * 2)];
2137                 /* This won't overflow because there is +1 entry in the table */
2138                 code_end = amodule->mono_eh_frame + table [(pos * 2) + 2];
2139         }
2140         code_len = code_end - code_start;
2141
2142         g_assert (code >= code_start && code < code_end);
2143
2144         if (amodule->thumb_end && (guint8*)code_start < amodule->thumb_end)
2145                 /* Clear thumb flag */
2146                 code_start = (guint8*)(((mgreg_t)code_start) & ~1);
2147
2148         fde = amodule->mono_eh_frame + table [(pos * 2) + 1];   
2149         /* This won't overflow because there is +1 entry in the table */
2150         fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
2151
2152         mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info);
2153         ei = info.ex_info;
2154         ei_len = info.ex_info_len;
2155         type_info = info.type_info;
2156         *this_reg = info.this_reg;
2157         *this_offset = info.this_offset;
2158
2159         /* Count number of nested clauses */
2160         nested_len = 0;
2161         for (i = 0; i < ei_len; ++i) {
2162                 /* This might be unaligned */
2163                 gint32 cindex1 = read32 (type_info [i]);
2164                 GSList *l;
2165
2166                 for (l = nesting [cindex1]; l; l = l->next) {
2167                         gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2168
2169                         for (j = 0; j < ei_len; ++j) {
2170                                 gint32 cindex2 = read32 (type_info [j]);
2171
2172                                 if (cindex2 == nesting_cindex)
2173                                         nested_len ++;
2174                         }
2175                 }
2176         }
2177
2178         /*
2179          * LLVM might represent one IL region with multiple regions, so have to
2180          * allocate a new JI.
2181          */
2182         jinfo = 
2183                 mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * (ei_len + nested_len)) + extra_size);
2184
2185         jinfo->code_size = code_len;
2186         jinfo->used_regs = mono_cache_unwind_info (info.unw_info, info.unw_info_len);
2187         jinfo->method = method;
2188         jinfo->code_start = code;
2189         jinfo->domain_neutral = 0;
2190         /* This signals that used_regs points to a normal cached unwind info */
2191         jinfo->from_aot = 0;
2192         jinfo->num_clauses = ei_len + nested_len;
2193
2194         for (i = 0; i < ei_len; ++i) {
2195                 /*
2196                  * orig_jinfo contains the original IL exception info saved by the AOT
2197                  * compiler, we have to combine that with the information produced by LLVM
2198                  */
2199                 /* The type_info entries contain IL clause indexes */
2200                 int clause_index = read32 (type_info [i]);
2201                 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
2202                 MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
2203
2204                 g_assert (clause_index < num_clauses);
2205                 jei->flags = orig_jei->flags;
2206                 jei->data.catch_class = orig_jei->data.catch_class;
2207
2208                 jei->try_start = ei [i].try_start;
2209                 jei->try_end = ei [i].try_end;
2210                 jei->handler_start = ei [i].handler_start;
2211
2212                 /* Make sure we transition to thumb when a handler starts */
2213                 if (amodule->thumb_end && (guint8*)jei->handler_start < amodule->thumb_end)
2214                         jei->handler_start = (void*)((mgreg_t)jei->handler_start + 1);
2215         }
2216
2217         /* See exception_cb () in mini-llvm.c as to why this is needed */
2218         nindex = ei_len;
2219         for (i = 0; i < ei_len; ++i) {
2220                 gint32 cindex1 = read32 (type_info [i]);
2221                 GSList *l;
2222
2223                 for (l = nesting [cindex1]; l; l = l->next) {
2224                         gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2225
2226                         for (j = 0; j < ei_len; ++j) {
2227                                 gint32 cindex2 = read32 (type_info [j]);
2228
2229                                 if (cindex2 == nesting_cindex) {
2230                                         /* 
2231                                          * The try interval comes from the nested clause, everything else from the
2232                                          * nesting clause.
2233                                          */
2234                                         memcpy (&jinfo->clauses [nindex], &jinfo->clauses [j], sizeof (MonoJitExceptionInfo));
2235                                         jinfo->clauses [nindex].try_start = jinfo->clauses [i].try_start;
2236                                         jinfo->clauses [nindex].try_end = jinfo->clauses [i].try_end;
2237                                         nindex ++;
2238                                 }
2239                         }
2240                 }
2241         }
2242         g_assert (nindex == ei_len + nested_len);
2243
2244         return jinfo;
2245 }
2246
2247 /*
2248  * LOCKING: Acquires the domain lock.
2249  */
2250 static MonoJitInfo*
2251 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain, 
2252                                                          MonoMethod *method, guint8* ex_info, guint8 *addr,
2253                                                          guint8 *code, guint32 code_len)
2254 {
2255         int i, buf_len, num_clauses;
2256         MonoJitInfo *jinfo;
2257         guint used_int_regs, flags;
2258         gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes, has_arch_eh_jit_info;
2259         gboolean from_llvm, has_gc_map;
2260         guint8 *p;
2261         int generic_info_size, try_holes_info_size, num_holes, arch_eh_jit_info_size;
2262         int this_reg = 0, this_offset = 0;
2263
2264         /* Load the method info from the AOT file */
2265
2266         p = ex_info;
2267         flags = decode_value (p, &p);
2268         has_generic_jit_info = (flags & 1) != 0;
2269         has_dwarf_unwind_info = (flags & 2) != 0;
2270         has_clauses = (flags & 4) != 0;
2271         has_seq_points = (flags & 8) != 0;
2272         from_llvm = (flags & 16) != 0;
2273         has_try_block_holes = (flags & 32) != 0;
2274         has_gc_map = (flags & 64) != 0;
2275         has_arch_eh_jit_info = (flags & 128) != 0;
2276
2277         if (has_dwarf_unwind_info) {
2278                 guint32 offset;
2279
2280                 offset = decode_value (p, &p);
2281                 g_assert (offset < (1 << 30));
2282                 used_int_regs = offset;
2283         } else {
2284                 used_int_regs = decode_value (p, &p);
2285         }
2286         if (has_generic_jit_info)
2287                 generic_info_size = sizeof (MonoGenericJitInfo);
2288         else
2289                 generic_info_size = 0;
2290
2291         if (has_try_block_holes) {
2292                 num_holes = decode_value (p, &p);
2293                 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
2294         } else {
2295                 num_holes = try_holes_info_size = 0;
2296         }
2297         /* Exception table */
2298         if (has_clauses)
2299                 num_clauses = decode_value (p, &p);
2300         else
2301                 num_clauses = 0;
2302         if (has_arch_eh_jit_info)
2303                 arch_eh_jit_info_size = sizeof (MonoArchEHJitInfo);
2304         else
2305                 arch_eh_jit_info_size = 0;
2306
2307         if (from_llvm) {
2308                 MonoJitExceptionInfo *clauses;
2309                 GSList **nesting;
2310
2311                 /*
2312                  * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
2313                  * section.
2314                  */
2315                 clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
2316                 nesting = g_new0 (GSList*, num_clauses);
2317
2318                 for (i = 0; i < num_clauses; ++i) {
2319                         MonoJitExceptionInfo *ei = &clauses [i];
2320
2321                         ei->flags = decode_value (p, &p);
2322
2323                         if (decode_value (p, &p))
2324                                 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2325
2326                         /* Read the list of nesting clauses */
2327                         while (TRUE) {
2328                                 int nesting_index = decode_value (p, &p);
2329                                 if (nesting_index == -1)
2330                                         break;
2331                                 nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
2332                         }
2333                 }
2334
2335                 jinfo = decode_llvm_mono_eh_frame (amodule, domain, method, code, clauses, num_clauses, generic_info_size + try_holes_info_size + arch_eh_jit_info_size, nesting, &this_reg, &this_offset);
2336                 jinfo->from_llvm = 1;
2337
2338                 g_free (clauses);
2339                 for (i = 0; i < num_clauses; ++i)
2340                         g_slist_free (nesting [i]);
2341                 g_free (nesting);
2342         } else {
2343                 jinfo = 
2344                         mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size + arch_eh_jit_info_size);
2345                 jinfo->num_clauses = num_clauses;
2346
2347                 for (i = 0; i < jinfo->num_clauses; ++i) {
2348                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2349
2350                         ei->flags = decode_value (p, &p);
2351
2352                         ei->exvar_offset = decode_value (p, &p);
2353
2354                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
2355                                 ei->data.filter = code + decode_value (p, &p);
2356                         else {
2357                                 if (decode_value (p, &p))
2358                                         ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2359                         }
2360
2361                         ei->try_start = code + decode_value (p, &p);
2362                         ei->try_end = code + decode_value (p, &p);
2363                         ei->handler_start = code + decode_value (p, &p);
2364                 }
2365
2366                 jinfo->code_size = code_len;
2367                 jinfo->used_regs = used_int_regs;
2368                 jinfo->method = method;
2369                 jinfo->code_start = code;
2370                 jinfo->domain_neutral = 0;
2371                 jinfo->from_aot = 1;
2372         }
2373
2374         if (has_generic_jit_info) {
2375                 MonoGenericJitInfo *gi;
2376
2377                 jinfo->has_generic_jit_info = 1;
2378
2379                 gi = mono_jit_info_get_generic_jit_info (jinfo);
2380                 g_assert (gi);
2381
2382                 gi->nlocs = decode_value (p, &p);
2383                 if (gi->nlocs) {
2384                         gi->locations = mono_domain_alloc0 (domain, gi->nlocs * sizeof (MonoDwarfLocListEntry));
2385                         for (i = 0; i < gi->nlocs; ++i) {
2386                                 MonoDwarfLocListEntry *entry = &gi->locations [i];
2387
2388                                 entry->is_reg = decode_value (p, &p);
2389                                 entry->reg = decode_value (p, &p);
2390                                 if (!entry->is_reg)
2391                                         entry->offset = decode_value (p, &p);
2392                                 if (i > 0)
2393                                         entry->from = decode_value (p, &p);
2394                                 entry->to = decode_value (p, &p);
2395                         }
2396                 } else {
2397                         if (from_llvm) {
2398                                 gi->has_this = this_reg != -1;
2399                                 gi->this_reg = this_reg;
2400                                 gi->this_offset = this_offset;
2401                         } else {
2402                                 gi->has_this = decode_value (p, &p);
2403                                 gi->this_reg = decode_value (p, &p);
2404                                 gi->this_offset = decode_value (p, &p);
2405                         }
2406                 }
2407
2408                 jinfo->method = decode_resolve_method_ref (amodule, p, &p);
2409
2410                 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2411                 if (decode_value (p, &p)) {
2412                         /* gsharedvt */
2413                         int i, n;
2414                         MonoGenericSharingContext *gsctx = gi->generic_sharing_context;
2415
2416                         n = decode_value (p, &p);
2417                         if (n) {
2418                                 gsctx->var_is_vt = g_new0 (gboolean, n);
2419                                 for (i = 0; i < n; ++i)
2420                                         gsctx->var_is_vt [i] = decode_value (p, &p);
2421                         }
2422                         n = decode_value (p, &p);
2423                         if (n) {
2424                                 gsctx->mvar_is_vt = g_new0 (gboolean, n);
2425                                 for (i = 0; i < n; ++i)
2426                                         gsctx->mvar_is_vt [i] = decode_value (p, &p);
2427                         }
2428                 }
2429         }
2430
2431         if (has_try_block_holes) {
2432                 MonoTryBlockHoleTableJitInfo *table;
2433
2434                 jinfo->has_try_block_holes = 1;
2435
2436                 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2437                 g_assert (table);
2438
2439                 table->num_holes = (guint16)num_holes;
2440                 for (i = 0; i < num_holes; ++i) {
2441                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
2442                         hole->clause = decode_value (p, &p);
2443                         hole->length = decode_value (p, &p);
2444                         hole->offset = decode_value (p, &p);
2445                 }
2446         }
2447
2448         if (has_arch_eh_jit_info) {
2449                 MonoArchEHJitInfo *eh_info;
2450
2451                 jinfo->has_arch_eh_info = 1;
2452
2453                 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
2454                 eh_info->stack_size = decode_value (p, &p);
2455         }
2456
2457         if (has_seq_points) {
2458                 MonoSeqPointInfo *seq_points;
2459                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
2460
2461                 int len = decode_value (p, &p);
2462
2463                 seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
2464                 seq_points->len = len;
2465                 last_il_offset = last_native_offset = 0;
2466                 for (i = 0; i < len; ++i) {
2467                         SeqPoint *sp = &seq_points->seq_points [i];
2468                         il_offset = last_il_offset + decode_value (p, &p);
2469                         native_offset = last_native_offset + decode_value (p, &p);
2470
2471                         sp->il_offset = il_offset;
2472                         sp->native_offset = native_offset;
2473                         
2474                         sp->next_len = decode_value (p, &p);
2475                         sp->next = g_new (int, sp->next_len);
2476                         for (j = 0; j < sp->next_len; ++j)
2477                                 sp->next [j] = decode_value (p, &p);
2478
2479                         last_il_offset = il_offset;
2480                         last_native_offset = native_offset;
2481                 }
2482
2483                 mono_domain_lock (domain);
2484                 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
2485                 mono_domain_unlock (domain);
2486         }
2487
2488         /* Load debug info */
2489         buf_len = decode_value (p, &p);
2490         mono_debug_add_aot_method (domain, method, code, p, buf_len);
2491         p += buf_len;
2492
2493         if (has_gc_map) {
2494                 int map_size = decode_value (p, &p);
2495                 /* The GC map requires 4 bytes of alignment */
2496                 while ((guint64)(gsize)p % 4)
2497                         p ++;           
2498                 jinfo->gc_info = p;
2499                 p += map_size;
2500         }
2501
2502         if (amodule != jinfo->method->klass->image->aot_module) {
2503                 mono_aot_lock ();
2504                 if (!ji_to_amodule)
2505                         ji_to_amodule = g_hash_table_new (NULL, NULL);
2506                 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
2507                 mono_aot_unlock ();             
2508         }
2509
2510         return jinfo;
2511 }
2512
2513 /*
2514  * mono_aot_get_unwind_info:
2515  *
2516  *   Return a pointer to the DWARF unwind info belonging to JI.
2517  */
2518 guint8*
2519 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
2520 {
2521         MonoAotModule *amodule = ji->method->klass->image->aot_module;
2522         guint8 *p;
2523         guint8 *code = ji->code_start;
2524
2525         g_assert (amodule);
2526         g_assert (ji->from_aot);
2527
2528         if (!(code >= amodule->code && code <= amodule->code_end)) {
2529                 /* ji belongs to a different aot module than amodule */
2530                 mono_aot_lock ();
2531                 g_assert (ji_to_amodule);
2532                 amodule = g_hash_table_lookup (ji_to_amodule, ji);
2533                 g_assert (amodule);
2534                 g_assert (code >= amodule->code && code <= amodule->code_end);
2535                 mono_aot_unlock ();
2536         }
2537
2538         p = amodule->unwind_info + ji->used_regs;
2539         *unwind_info_len = decode_value (p, &p);
2540         return p;
2541 }
2542
2543 static G_GNUC_UNUSED int
2544 compare_ints (const void *a, const void *b)
2545 {
2546         return *(gint32*)a - *(gint32*)b;
2547 }
2548
2549 static void
2550 msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch)
2551 {
2552         int mid = (lo + hi) / 2;
2553         int i, t_lo, t_hi;
2554
2555         if (lo >= hi)
2556                 return;
2557
2558         if (hi - lo < 32) {
2559                 for (i = lo; i < hi; ++i)
2560                         if (array [(i * 2)] > array [(i * 2) + 2])
2561                                 break;
2562                 if (i == hi)
2563                         /* Already sorted */
2564                         return;
2565         }
2566
2567         msort_code_offsets_internal (array, lo, mid, scratch);
2568         msort_code_offsets_internal (array, mid + 1, hi, scratch);
2569
2570         if (array [mid * 2] < array [(mid + 1) * 2])
2571                 return;
2572
2573         /* Merge */
2574         t_lo = lo;
2575         t_hi = mid + 1;
2576         for (i = lo; i <= hi; i ++) {
2577                 if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) {
2578                         scratch [(i * 2)] = array [t_lo * 2];
2579                         scratch [(i * 2) + 1] = array [(t_lo *2) + 1];
2580                         t_lo ++;
2581                 } else {
2582                         scratch [(i * 2)] = array [t_hi * 2];
2583                         scratch [(i * 2) + 1] = array [(t_hi *2) + 1];
2584                         t_hi ++;
2585                 }
2586         }
2587         for (i = lo; i <= hi; ++i) {
2588                 array [(i * 2)] = scratch [i * 2];
2589                 array [(i * 2) + 1] = scratch [(i * 2) + 1];
2590         }
2591 }
2592
2593 static void
2594 msort_code_offsets (gint32 *array, int len)
2595 {
2596         gint32 *scratch;
2597
2598         scratch = g_new (gint32, len * 2);
2599         msort_code_offsets_internal (array, 0, len - 1, scratch);
2600         g_free (scratch);
2601 }
2602
2603 MonoJitInfo *
2604 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
2605 {
2606         int pos, left, right, offset, offset1, offset2, code_len;
2607         int method_index, table_len;
2608         guint32 token;
2609         MonoAotModule *amodule = image->aot_module;
2610         MonoMethod *method;
2611         MonoJitInfo *jinfo;
2612         guint8 *code, *ex_info, *p;
2613         guint32 *table;
2614         int nmethods = amodule->info.nmethods;
2615         gint32 *code_offsets;
2616         int offsets_len, i;
2617
2618         if (!amodule)
2619                 return NULL;
2620
2621         if (domain != mono_get_root_domain ())
2622                 /* FIXME: */
2623                 return NULL;
2624
2625         offset = (guint8*)addr - amodule->code;
2626
2627         /* Compute a sorted table mapping code offsets to method indexes. */
2628         if (!amodule->sorted_code_offsets) {
2629                 code_offsets = g_new0 (gint32, nmethods * 2);
2630                 offsets_len = 0;
2631                 for (i = 0; i < nmethods; ++i) {
2632                         /* Skip the -1 entries to speed up sorting */
2633                         if (amodule->code_offsets [i] == 0xffffffff)
2634                                 continue;
2635                         code_offsets [(offsets_len * 2)] = amodule->code_offsets [i];
2636                         code_offsets [(offsets_len *2) + 1] = i;
2637                         offsets_len ++;
2638                 }
2639                 /* Use a merge sort as this is mostly sorted */
2640                 msort_code_offsets (code_offsets, offsets_len);
2641                 //qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints);
2642                 for (i = 0; i < offsets_len -1; ++i)
2643                         g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);
2644
2645                 amodule->sorted_code_offsets_len = offsets_len;
2646                 mono_memory_barrier ();
2647                 if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
2648                         /* Somebody got in before us */
2649                         g_free (code_offsets);
2650         }
2651
2652         code_offsets = amodule->sorted_code_offsets;
2653         offsets_len = amodule->sorted_code_offsets_len;
2654
2655         if (offsets_len > 0 && (offset < code_offsets [0] || offset >= (amodule->code_end - amodule->code)))
2656                 return NULL;
2657
2658         /* Binary search in the sorted_code_offsets table */
2659         left = 0;
2660         right = offsets_len;
2661         while (TRUE) {
2662                 pos = (left + right) / 2;
2663
2664                 offset1 = code_offsets [(pos * 2)];
2665                 if (pos + 1 == offsets_len)
2666                         offset2 = amodule->code_end - amodule->code;
2667                 else
2668                         offset2 = code_offsets [(pos + 1) * 2];
2669
2670                 if (offset < offset1)
2671                         right = pos;
2672                 else if (offset >= offset2)
2673                         left = pos + 1;
2674                 else
2675                         break;
2676         }
2677
2678         g_assert (offset >= code_offsets [(pos * 2)]);
2679         if (pos + 1 < offsets_len)
2680                 g_assert (offset < code_offsets [((pos + 1) * 2)]);
2681         method_index = code_offsets [(pos * 2) + 1];
2682
2683         code = &amodule->code [amodule->code_offsets [method_index]];
2684         ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
2685
2686         if (pos == offsets_len - 1)
2687                 code_len = amodule->code_end - code;
2688         else
2689                 code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];
2690
2691         g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
2692
2693         /* Might be a wrapper/extra method */
2694         if (amodule->extra_methods) {
2695                 mono_aot_lock ();
2696                 method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
2697                 mono_aot_unlock ();
2698         } else {
2699                 method = NULL;
2700         }
2701
2702         if (!method) {
2703                 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
2704                         /* 
2705                          * This is hit for extra methods which are called directly, so they are
2706                          * not in amodule->extra_methods.
2707                          */
2708                         table_len = amodule->extra_method_info_offsets [0];
2709                         table = amodule->extra_method_info_offsets + 1;
2710                         left = 0;
2711                         right = table_len;
2712                         pos = 0;
2713
2714                         /* Binary search */
2715                         while (TRUE) {
2716                                 pos = ((left + right) / 2);
2717
2718                                 g_assert (pos < table_len);
2719
2720                                 if (table [pos * 2] < method_index)
2721                                         left = pos + 1;
2722                                 else if (table [pos * 2] > method_index)
2723                                         right = pos;
2724                                 else
2725                                         break;
2726                         }
2727
2728                         p = amodule->blob + table [(pos * 2) + 1];
2729                         method = decode_resolve_method_ref (amodule, p, &p);
2730                         if (!method)
2731                                 /* Happens when a random address is passed in which matches a not-yey called wrapper encoded using its name */
2732                                 return NULL;
2733                 } else {
2734                         token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
2735                         method = mono_get_method (image, token, NULL);
2736                 }
2737         }
2738
2739         /* FIXME: */
2740         g_assert (method);
2741
2742         //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2743         
2744         jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);
2745
2746         g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
2747         g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
2748
2749         /* Add it to the normal JitInfo tables */
2750         mono_jit_info_table_add (domain, jinfo);
2751         
2752         return jinfo;
2753 }
2754
2755 static gboolean
2756 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
2757 {
2758         guint8 *p = buf;
2759         gpointer *table;
2760         MonoImage *image;
2761         int i;
2762
2763         switch (ji->type) {
2764         case MONO_PATCH_INFO_METHOD:
2765         case MONO_PATCH_INFO_METHOD_JUMP:
2766         case MONO_PATCH_INFO_ICALL_ADDR:
2767         case MONO_PATCH_INFO_METHOD_RGCTX: {
2768                 MethodRef ref;
2769                 gboolean res;
2770
2771                 res = decode_method_ref (aot_module, &ref, p, &p);
2772                 if (!res)
2773                         goto cleanup;
2774
2775                 if (!ref.method && !mono_aot_only && !ref.no_aot_trampoline && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (ref.token) == MONO_TABLE_METHOD)) {
2776                         ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (ref.image, ref.token));
2777                         ji->type = MONO_PATCH_INFO_ABS;
2778                 }
2779                 else {
2780                         if (ref.method)
2781                                 ji->data.method = ref.method;
2782                         else
2783                                 ji->data.method = mono_get_method (ref.image, ref.token, NULL);
2784                         g_assert (ji->data.method);
2785                         mono_class_init (ji->data.method->klass);
2786                 }
2787                 break;
2788         }
2789         case MONO_PATCH_INFO_INTERNAL_METHOD:
2790         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2791                 guint32 len = decode_value (p, &p);
2792
2793                 ji->data.name = (char*)p;
2794                 p += len + 1;
2795                 break;
2796         }
2797         case MONO_PATCH_INFO_METHODCONST:
2798                 /* Shared */
2799                 ji->data.method = decode_resolve_method_ref (aot_module, p, &p);
2800                 if (!ji->data.method)
2801                         goto cleanup;
2802                 break;
2803         case MONO_PATCH_INFO_VTABLE:
2804         case MONO_PATCH_INFO_CLASS:
2805         case MONO_PATCH_INFO_IID:
2806         case MONO_PATCH_INFO_ADJUSTED_IID:
2807                 /* Shared */
2808                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2809                 if (!ji->data.klass)
2810                         goto cleanup;
2811                 break;
2812         case MONO_PATCH_INFO_CLASS_INIT:
2813         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2814                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2815                 if (!ji->data.klass)
2816                         goto cleanup;
2817                 break;
2818         case MONO_PATCH_INFO_IMAGE:
2819                 ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE);
2820                 if (!ji->data.image)
2821                         goto cleanup;
2822                 break;
2823         case MONO_PATCH_INFO_FIELD:
2824         case MONO_PATCH_INFO_SFLDA:
2825                 /* Shared */
2826                 ji->data.field = decode_field_info (aot_module, p, &p);
2827                 if (!ji->data.field)
2828                         goto cleanup;
2829                 break;
2830         case MONO_PATCH_INFO_SWITCH:
2831                 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
2832                 ji->data.table->table_size = decode_value (p, &p);
2833                 table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
2834                 ji->data.table->table = (MonoBasicBlock**)table;
2835                 for (i = 0; i < ji->data.table->table_size; i++)
2836                         table [i] = (gpointer)(gssize)decode_value (p, &p);
2837                 break;
2838         case MONO_PATCH_INFO_R4: {
2839                 guint32 val;
2840                 
2841                 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
2842                 val = decode_value (p, &p);
2843                 *(float*)ji->data.target = *(float*)&val;
2844                 break;
2845         }
2846         case MONO_PATCH_INFO_R8: {
2847                 guint32 val [2];
2848                 guint64 v;
2849
2850                 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
2851
2852                 val [0] = decode_value (p, &p);
2853                 val [1] = decode_value (p, &p);
2854                 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
2855                 *(double*)ji->data.target = *(double*)&v;
2856                 break;
2857         }
2858         case MONO_PATCH_INFO_LDSTR:
2859                 image = load_image (aot_module, decode_value (p, &p), TRUE);
2860                 if (!image)
2861                         goto cleanup;
2862                 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
2863                 break;
2864         case MONO_PATCH_INFO_RVA:
2865         case MONO_PATCH_INFO_DECLSEC:
2866         case MONO_PATCH_INFO_LDTOKEN:
2867         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2868                 /* Shared */
2869                 image = load_image (aot_module, decode_value (p, &p), TRUE);
2870                 if (!image)
2871                         goto cleanup;
2872                 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
2873
2874                 ji->data.token->has_context = decode_value (p, &p);
2875                 if (ji->data.token->has_context) {
2876                         gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
2877                         if (!res)
2878                                 goto cleanup;
2879                 }
2880                 break;
2881         case MONO_PATCH_INFO_EXC_NAME:
2882                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2883                 if (!ji->data.klass)
2884                         goto cleanup;
2885                 ji->data.name = ji->data.klass->name;
2886                 break;
2887         case MONO_PATCH_INFO_METHOD_REL:
2888                 ji->data.offset = decode_value (p, &p);
2889                 break;
2890         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2891         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2892         case MONO_PATCH_INFO_MONITOR_ENTER:
2893         case MONO_PATCH_INFO_MONITOR_EXIT:
2894         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
2895         case MONO_PATCH_INFO_CASTCLASS_CACHE:
2896         case MONO_PATCH_INFO_JIT_TLS_ID:
2897                 break;
2898         case MONO_PATCH_INFO_RGCTX_FETCH: {
2899                 gboolean res;
2900                 MonoJumpInfoRgctxEntry *entry;
2901                 guint32 offset, val;
2902                 guint8 *p2;
2903
2904                 offset = decode_value (p, &p);
2905                 val = decode_value (p, &p);
2906
2907                 entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
2908                 p2 = aot_module->blob + offset;
2909                 entry->method = decode_resolve_method_ref (aot_module, p2, &p2);
2910                 entry->in_mrgctx = ((val & 1) > 0) ? TRUE : FALSE;
2911                 entry->info_type = (val >> 1) & 0xff;
2912                 entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
2913                 entry->data->type = (val >> 9) & 0xff;
2914                 
2915                 res = decode_patch (aot_module, mp, entry->data, p, &p);
2916                 if (!res)
2917                         goto cleanup;
2918                 ji->data.rgctx_entry = entry;
2919                 break;
2920         }
2921         case MONO_PATCH_INFO_SEQ_POINT_INFO:
2922                 break;
2923         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
2924                 MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));
2925
2926                 imt_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
2927                 imt_tramp->vt_offset = decode_value (p, &p);
2928                 
2929                 ji->data.imt_tramp = imt_tramp;
2930                 break;
2931         }
2932         case MONO_PATCH_INFO_SIGNATURE:
2933                 ji->data.target = decode_signature (aot_module, p, &p);
2934                 break;
2935         case MONO_PATCH_INFO_GSHAREDVT_CALL: {
2936                 MonoJumpInfoGSharedVtCall *info = g_new0 (MonoJumpInfoGSharedVtCall, 1);
2937                 info->sig = decode_signature (aot_module, p, &p);
2938                 g_assert (info->sig);
2939                 info->method = decode_resolve_method_ref (aot_module, p, &p);
2940                 g_assert (info->method);
2941
2942                 ji->data.target = info;
2943                 break;
2944         }
2945         default:
2946                 g_warning ("unhandled type %d", ji->type);
2947                 g_assert_not_reached ();
2948         }
2949
2950         *endbuf = p;
2951
2952         return TRUE;
2953
2954  cleanup:
2955         return FALSE;
2956 }
2957
2958 static MonoJumpInfo*
2959 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches, 
2960                                  guint32 **got_slots, 
2961                                  guint8 *buf, guint8 **endbuf)
2962 {
2963         MonoJumpInfo *patches;
2964         int pindex;
2965         guint8 *p;
2966
2967         p = buf;
2968
2969         patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
2970
2971         *got_slots = g_malloc (sizeof (guint32) * n_patches);
2972
2973         for (pindex = 0; pindex < n_patches; ++pindex) {
2974                 MonoJumpInfo *ji = &patches [pindex];
2975                 guint8 *shared_p;
2976                 gboolean res;
2977                 guint32 got_offset;
2978
2979                 got_offset = decode_value (p, &p);
2980
2981                 if (aot_module->got [got_offset]) {
2982                         /* Already loaded */
2983                         //printf ("HIT!\n");
2984                 } else {
2985                         shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);
2986
2987                         ji->type = decode_value (shared_p, &shared_p);
2988
2989                         res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
2990                         if (!res)
2991                                 goto cleanup;
2992                 }
2993
2994                 (*got_slots) [pindex] = got_offset;
2995         }
2996
2997         *endbuf = p;
2998         return patches;
2999
3000  cleanup:
3001         g_free (*got_slots);
3002         *got_slots = NULL;
3003
3004         return NULL;
3005 }
3006
3007 static void
3008 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
3009 {
3010         /*
3011          * Jump addresses cannot be patched by the trampoline code since it
3012          * does not have access to the caller's address. Instead, we collect
3013          * the addresses of the GOT slots pointing to a method, and patch
3014          * them after the method has been compiled.
3015          */
3016         MonoJitDomainInfo *info = domain_jit_info (domain);
3017         GSList *list;
3018                 
3019         mono_domain_lock (domain);
3020         if (!info->jump_target_got_slot_hash)
3021                 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
3022         list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
3023         list = g_slist_prepend (list, got_slot);
3024         g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
3025         mono_domain_unlock (domain);
3026 }
3027
3028 /*
3029  * load_method:
3030  *
3031  *   Load the method identified by METHOD_INDEX from the AOT image. Return a
3032  * pointer to the native code of the method, or NULL if not found.
3033  * METHOD might not be set if the caller only has the image/token info.
3034  */
3035 static gpointer
3036 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
3037 {
3038         MonoClass *klass;
3039         gboolean from_plt = method == NULL;
3040         MonoMemPool *mp;
3041         int i, pindex, n_patches, used_strings;
3042         gboolean keep_patches = TRUE;
3043         guint8 *p;
3044         MonoJitInfo *jinfo = NULL;
3045         guint8 *code, *info;
3046
3047         if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
3048                 return NULL;
3049
3050         if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
3051                 /* Non shared AOT code can't be used in other appdomains */
3052                 return NULL;
3053
3054         if (amodule->out_of_date)
3055                 return NULL;
3056
3057         if (amodule->code_offsets [method_index] == 0xffffffff) {
3058                 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3059                         char *full_name;
3060
3061                         if (!method)
3062                                 method = mono_get_method (image, token, NULL);
3063                         full_name = mono_method_full_name (method, TRUE);
3064                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.", full_name);
3065                         g_free (full_name);
3066                 }
3067                 return NULL;
3068         }
3069
3070         code = &amodule->code [amodule->code_offsets [method_index]];
3071
3072         info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
3073
3074         if (amodule->thumb_end && code < amodule->thumb_end && ((amodule->info.flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES) == 0)) {
3075                 /* Convert this into a thumb address */
3076                 g_assert ((amodule->code_offsets [method_index] & 0x1) == 0);
3077                 code = &amodule->code [amodule->code_offsets [method_index] + 1];
3078         }
3079
3080         mono_aot_lock ();
3081         if (!amodule->methods_loaded)
3082                 amodule->methods_loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
3083         mono_aot_unlock ();
3084
3085         if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
3086                 return code;
3087
3088         if (mono_last_aot_method != -1) {
3089                 if (mono_jit_stats.methods_aot >= mono_last_aot_method)
3090                                 return NULL;
3091                 else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
3092                         if (!method)
3093                                 method = mono_get_method (image, token, NULL);
3094                         if (method) {
3095                                 char *name = mono_method_full_name (method, TRUE);
3096                                 printf ("LAST AOT METHOD: %s.\n", name);
3097                                 g_free (name);
3098                         } else {
3099                                 printf ("LAST AOT METHOD: %p %d\n", code, method_index);
3100                         }
3101                 }
3102         }
3103
3104         p = info;
3105
3106         if (method) {
3107                 klass = method->klass;
3108                 decode_klass_ref (amodule, p, &p);
3109         } else {
3110                 klass = decode_klass_ref (amodule, p, &p);
3111         }
3112
3113         if (amodule->info.opts & MONO_OPT_SHARED)
3114                 used_strings = decode_value (p, &p);
3115         else
3116                 used_strings = 0;
3117
3118         for (i = 0; i < used_strings; i++) {
3119                 guint token = decode_value (p, &p);
3120                 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
3121         }
3122
3123         if (amodule->info.opts & MONO_OPT_SHARED)       
3124                 keep_patches = FALSE;
3125
3126         n_patches = decode_value (p, &p);
3127
3128         keep_patches = FALSE;
3129
3130         if (n_patches) {
3131                 MonoJumpInfo *patches;
3132                 guint32 *got_slots;
3133
3134                 if (keep_patches)
3135                         mp = domain->mp;
3136                 else
3137                         mp = mono_mempool_new ();
3138
3139                 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3140                 if (patches == NULL)
3141                         goto cleanup;
3142
3143                 for (pindex = 0; pindex < n_patches; ++pindex) {
3144                         MonoJumpInfo *ji = &patches [pindex];
3145
3146                         if (!amodule->got [got_slots [pindex]]) {
3147                                 amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
3148                                 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
3149                                         amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
3150                                 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
3151                                         register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
3152                         }
3153                         ji->type = MONO_PATCH_INFO_NONE;
3154                 }
3155
3156                 g_free (got_slots);
3157
3158                 if (!keep_patches)
3159                         mono_mempool_destroy (mp);
3160         }
3161
3162         if (mini_get_debug_options ()->load_aot_jit_info_eagerly)
3163                 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
3164
3165         if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3166                 char *full_name;
3167
3168                 if (!method)
3169                         method = mono_get_method (image, token, NULL);
3170
3171                 full_name = mono_method_full_name (method, TRUE);
3172
3173                 if (!jinfo)
3174                         jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
3175
3176                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND method %s [%p - %p %p]", full_name, code, code + jinfo->code_size, info);
3177                 g_free (full_name);
3178         }
3179
3180         mono_aot_lock ();
3181
3182         InterlockedIncrement (&mono_jit_stats.methods_aot);
3183
3184         amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
3185
3186         init_plt (amodule);
3187
3188         if (method && method->wrapper_type)
3189                 g_hash_table_insert (amodule->method_to_code, method, code);
3190
3191         mono_aot_unlock ();
3192
3193         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
3194                 MonoJitInfo *jinfo;
3195
3196                 if (!method) {
3197                         method = mono_get_method (image, token, NULL);
3198                         g_assert (method);
3199                 }
3200                 mono_profiler_method_jit (method);
3201                 jinfo = mono_jit_info_table_find (domain, (char*)code);
3202                 g_assert (jinfo);
3203                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
3204         }
3205
3206         if (from_plt && klass && !klass->generic_container)
3207                 mono_runtime_class_init (mono_class_vtable (domain, klass));
3208
3209         return code;
3210
3211  cleanup:
3212         /* FIXME: The space in domain->mp is wasted */  
3213         if (amodule->info.opts & MONO_OPT_SHARED)
3214                 /* No need to cache patches */
3215                 mono_mempool_destroy (mp);
3216
3217         if (jinfo)
3218                 g_free (jinfo);
3219
3220         return NULL;
3221 }
3222
3223 static guint32
3224 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method)
3225 {
3226         guint32 table_size, entry_size, hash;
3227         guint32 *table, *entry;
3228         guint32 index;
3229         static guint32 n_extra_decodes;
3230
3231         if (!amodule || amodule->out_of_date)
3232                 return 0xffffff;
3233
3234         table_size = amodule->extra_method_table [0];
3235         table = amodule->extra_method_table + 1;
3236         entry_size = 3;
3237
3238         hash = mono_aot_method_hash (method) % table_size;
3239
3240         entry = &table [hash * entry_size];
3241
3242         if (entry [0] == 0)
3243                 return 0xffffff;
3244
3245         index = 0xffffff;
3246         while (TRUE) {
3247                 guint32 key = entry [0];
3248                 guint32 value = entry [1];
3249                 guint32 next = entry [entry_size - 1];
3250                 MonoMethod *m;
3251                 guint8 *p, *orig_p;
3252
3253                 p = amodule->blob + key;
3254                 orig_p = p;
3255
3256                 mono_aot_lock ();
3257                 if (!amodule->method_ref_to_method)
3258                         amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
3259                 m = g_hash_table_lookup (amodule->method_ref_to_method, p);
3260                 mono_aot_unlock ();
3261                 if (!m) {
3262                         m = decode_resolve_method_ref_with_target (amodule, method, p, &p);
3263                         if (m) {
3264                                 mono_aot_lock ();
3265                                 g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
3266                                 mono_aot_unlock ();
3267                         }
3268                 }
3269                 if (m == method) {
3270                         index = value;
3271                         break;
3272                 }
3273
3274                 /* Special case: wrappers of shared generic methods */
3275                 if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
3276                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
3277                         MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
3278                         MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
3279
3280                         if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
3281                                 index = value;
3282                                 break;
3283                         }
3284                 }
3285
3286                 /* Methods decoded needlessly */
3287                 if (m) {
3288                         //printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
3289                         n_extra_decodes ++;
3290                 }
3291
3292                 if (next != 0)
3293                         entry = &table [next * entry_size];
3294                 else
3295                         break;
3296         }
3297
3298         return index;
3299 }
3300
3301 static void
3302 add_module_cb (gpointer key, gpointer value, gpointer user_data)
3303 {
3304         g_ptr_array_add ((GPtrArray*)user_data, value);
3305 }
3306
3307 /*
3308  * find_extra_method:
3309  *
3310  *   Try finding METHOD in the extra_method table in all AOT images.
3311  * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
3312  * module where the method was found.
3313  */
3314 static guint32
3315 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
3316 {
3317         guint32 index;
3318         GPtrArray *modules;
3319         int i;
3320
3321         /* Try the method's module first */
3322         *out_amodule = method->klass->image->aot_module;
3323         index = find_extra_method_in_amodule (method->klass->image->aot_module, method);
3324         if (index != 0xffffff)
3325                 return index;
3326
3327         /* 
3328          * Try all other modules.
3329          * This is needed because generic instances klass->image points to the image
3330          * containing the generic definition, but the native code is generated to the
3331          * AOT image which contains the reference.
3332          */
3333
3334         /* Make a copy to avoid doing the search inside the aot lock */
3335         modules = g_ptr_array_new ();
3336         mono_aot_lock ();
3337         g_hash_table_foreach (aot_modules, add_module_cb, modules);
3338         mono_aot_unlock ();
3339
3340         index = 0xffffff;
3341         for (i = 0; i < modules->len; ++i) {
3342                 MonoAotModule *amodule = g_ptr_array_index (modules, i);
3343
3344                 if (amodule != method->klass->image->aot_module)
3345                         index = find_extra_method_in_amodule (amodule, method);
3346                 if (index != 0xffffff) {
3347                         *out_amodule = amodule;
3348                         break;
3349                 }
3350         }
3351         
3352         g_ptr_array_free (modules, TRUE);
3353
3354         return index;
3355 }
3356
3357 /*
3358  * mono_aot_get_method:
3359  *
3360  *   Return a pointer to the AOTed native code for METHOD if it can be found,
3361  * NULL otherwise.
3362  * On platforms with function pointers, this doesn't return a function pointer.
3363  */
3364 gpointer
3365 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
3366 {
3367         MonoClass *klass = method->klass;
3368         guint32 method_index;
3369         MonoAotModule *amodule = klass->image->aot_module;
3370         guint8 *code;
3371
3372         if (!amodule)
3373                 return NULL;
3374
3375         if (amodule->out_of_date)
3376                 return NULL;
3377
3378         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3379                 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3380                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3381                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3382                 return NULL;
3383
3384         /*
3385          * Use the original method instead of its invoke-with-check wrapper.
3386          * This is not a problem when using full-aot, since it doesn't support
3387          * remoting.
3388          */
3389         if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3390                 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));
3391
3392         g_assert (klass->inited);
3393
3394         /* Find method index */
3395         if (method->is_inflated && !method->wrapper_type && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE, FALSE)) {
3396                 /* 
3397                  * For generic methods, we store the fully shared instance in place of the
3398                  * original method.
3399                  */
3400                 method = mono_method_get_declaring_generic_method (method);
3401                 method_index = mono_metadata_token_index (method->token) - 1;
3402         } else if (method->is_inflated || !method->token) {
3403                 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
3404                 mono_aot_lock ();
3405                 code = g_hash_table_lookup (amodule->method_to_code, method);
3406                 mono_aot_unlock ();
3407                 if (code)
3408                         return code;
3409
3410                 method_index = find_extra_method (method, &amodule);
3411                 /*
3412                  * Special case the ICollection<T> wrappers for arrays, as they cannot
3413                  * be statically enumerated, and each wrapper ends up calling the same
3414                  * method in Array.
3415                  */
3416                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
3417                         MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3418
3419                         code = mono_aot_get_method (domain, m);
3420                         if (code) {
3421                                 if (mono_method_needs_static_rgctx_invoke (m, FALSE)) {
3422                                         code = mono_create_static_rgctx_trampoline (m, mono_create_ftnptr (domain, code));
3423                                         /* The call above returns an ftnptr */
3424                                         code = mono_get_addr_from_ftnptr (code);
3425                                 }
3426
3427                                 return code;
3428                         }
3429                 }
3430
3431                 /*
3432                  * Special case Array.GetGenericValueImpl which is a generic icall.
3433                  * Generic sharing currently can't handle it, but the icall returns data using
3434                  * an out parameter, so the managed-to-native wrappers can share the same code.
3435                  */
3436                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
3437                         MonoMethod *m;
3438                         MonoGenericContext ctx;
3439                         MonoType *args [16];
3440
3441                         if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
3442                                 /* Avoid recursion */
3443                                 return NULL;
3444
3445                         m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
3446                         g_assert (m);
3447
3448                         memset (&ctx, 0, sizeof (ctx));
3449                         args [0] = &mono_defaults.object_class->byval_arg;
3450                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3451
3452                         m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3453
3454                         /* 
3455                          * Get the code for the <object> instantiation which should be emitted into
3456                          * the mscorlib aot image by the AOT compiler.
3457                          */
3458                         code = mono_aot_get_method (domain, m);
3459                         if (code)
3460                                 return code;
3461                 }
3462
3463                 /* Same for CompareExchange<T> and Exchange<T> */
3464                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass->image == mono_defaults.corlib && !strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Interlocked") && (!strcmp (method->name, "CompareExchange") || !strcmp (method->name, "Exchange")) && MONO_TYPE_IS_REFERENCE (mono_method_signature (method)->params [1])) {
3465                         MonoMethod *m;
3466                         MonoGenericContext ctx;
3467                         MonoType *args [16];
3468                         gpointer iter = NULL;
3469
3470                         while ((m = mono_class_get_methods (method->klass, &iter))) {
3471                                 if (mono_method_signature (m)->generic_param_count && !strcmp (m->name, method->name))
3472                                         break;
3473                         }
3474                         g_assert (m);
3475
3476                         memset (&ctx, 0, sizeof (ctx));
3477                         args [0] = &mono_defaults.object_class->byval_arg;
3478                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3479
3480                         m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3481
3482                         /* Avoid recursion */
3483                         if (method == m)
3484                                 return NULL;
3485
3486                         /* 
3487                          * Get the code for the <object> instantiation which should be emitted into
3488                          * the mscorlib aot image by the AOT compiler.
3489                          */
3490                         code = mono_aot_get_method (domain, m);
3491                         if (code)
3492                                 return code;
3493                 }
3494
3495                 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE, TRUE)) {
3496                         /* gsharedvt */
3497                         /* Use the all-vt shared method since this is what was AOTed */
3498                         method_index = find_extra_method (mini_get_shared_method_full (method, TRUE, TRUE), &amodule);
3499                         if (method_index != 0xffffff)
3500                                 method = mini_get_shared_method_full (method, TRUE, FALSE);
3501                 }
3502
3503                 if (method_index == 0xffffff) {
3504                         if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3505                                 char *full_name;
3506
3507                                 full_name = mono_method_full_name (method, TRUE);
3508                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
3509                                 g_free (full_name);
3510                         }
3511                         return NULL;
3512                 }
3513
3514                 if (method_index == 0xffffff)
3515                         return NULL;
3516
3517                 /* Needed by find_jit_info */
3518                 mono_aot_lock ();
3519                 if (!amodule->extra_methods)
3520                         amodule->extra_methods = g_hash_table_new (NULL, NULL);
3521                 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
3522                 mono_aot_unlock ();
3523         } else {
3524                 /* Common case */
3525                 method_index = mono_metadata_token_index (method->token) - 1;
3526         }
3527
3528         return load_method (domain, amodule, klass->image, method, method->token, method_index);
3529 }
3530
3531 /**
3532  * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
3533  * method.
3534  */
3535 gpointer
3536 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3537 {
3538         MonoAotModule *aot_module = image->aot_module;
3539         int method_index;
3540
3541         if (!aot_module)
3542                 return NULL;
3543
3544         method_index = mono_metadata_token_index (token) - 1;
3545
3546         return load_method (domain, aot_module, image, NULL, token, method_index);
3547 }
3548
3549 typedef struct {
3550         guint8 *addr;
3551         gboolean res;
3552 } IsGotEntryUserData;
3553
3554 static void
3555 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
3556 {
3557         IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
3558         MonoAotModule *aot_module = (MonoAotModule*)value;
3559
3560         if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
3561                 data->res = TRUE;
3562 }
3563
3564 gboolean
3565 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3566 {
3567         IsGotEntryUserData user_data;
3568
3569         if (!aot_modules)
3570                 return FALSE;
3571
3572         user_data.addr = addr;
3573         user_data.res = FALSE;
3574         mono_aot_lock ();
3575         g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
3576         mono_aot_unlock ();
3577         
3578         return user_data.res;
3579 }
3580
3581 typedef struct {
3582         guint8 *addr;
3583         MonoAotModule *module;
3584 } FindAotModuleUserData;
3585
3586 static void
3587 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
3588 {
3589         FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
3590         MonoAotModule *aot_module = (MonoAotModule*)value;
3591
3592         if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
3593                 data->module = aot_module;
3594 }
3595
3596 static inline MonoAotModule*
3597 find_aot_module (guint8 *code)
3598 {
3599         FindAotModuleUserData user_data;
3600
3601         if (!aot_modules)
3602                 return NULL;
3603
3604         /* Reading these need no locking */
3605         if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
3606                 return NULL;
3607
3608         user_data.addr = code;
3609         user_data.module = NULL;
3610                 
3611         mono_aot_lock ();
3612         g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
3613         mono_aot_unlock ();
3614         
3615         return user_data.module;
3616 }
3617
3618 void
3619 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
3620 {
3621         /*
3622          * Since AOT code is only used in the root domain, 
3623          * mono_domain_get () != mono_get_root_domain () means the calling method
3624          * is AppDomain:InvokeInDomain, so this is the same check as in 
3625          * mono_method_same_domain () but without loading the metadata for the method.
3626          */
3627         if (mono_domain_get () == mono_get_root_domain ())
3628                 mono_arch_patch_plt_entry (code, got, regs, addr);
3629 }
3630
3631 /*
3632  * mono_aot_plt_resolve:
3633  *
3634  *   This function is called by the entries in the PLT to resolve the actual method that
3635  * needs to be called. It returns a trampoline to the method and patches the PLT entry.
3636  * Returns NULL if the something cannot be loaded.
3637  */
3638 gpointer
3639 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3640 {
3641 #ifdef MONO_ARCH_AOT_SUPPORTED
3642         guint8 *p, *target, *plt_entry;
3643         MonoJumpInfo ji;
3644         MonoAotModule *module = (MonoAotModule*)aot_module;
3645         gboolean res, no_ftnptr = FALSE;
3646         MonoMemPool *mp;
3647         gboolean using_gsharedvt = FALSE;
3648
3649         //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
3650
3651         p = &module->blob [plt_info_offset];
3652
3653         ji.type = decode_value (p, &p);
3654
3655         mp = mono_mempool_new_size (512);
3656         res = decode_patch (module, mp, &ji, p, &p);
3657
3658         if (!res) {
3659                 mono_mempool_destroy (mp);
3660                 return NULL;
3661         }
3662
3663 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
3664         using_gsharedvt = TRUE;
3665 #endif
3666
3667         /* 
3668          * Avoid calling resolve_patch_target in the full-aot case if possible, since
3669          * it would create a trampoline, and we don't need that.
3670          * We could do this only if the method does not need the special handling
3671          * in mono_magic_trampoline ().
3672          */
3673         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) &&
3674                 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE) && !using_gsharedvt) {
3675                 target = mono_jit_compile_method (ji.data.method);
3676                 no_ftnptr = TRUE;
3677         } else {
3678                 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
3679         }
3680
3681         /*
3682          * The trampoline expects us to return a function descriptor on platforms which use
3683          * it, but resolve_patch_target returns a direct function pointer for some type of
3684          * patches, so have to translate between the two.
3685          * FIXME: Clean this up, but how ?
3686          */
3687         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) {
3688                 /* These should already have a function descriptor */
3689 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3690                 /* Our function descriptors have a 0 environment, gcc created ones don't */
3691                 if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
3692                         g_assert (((gpointer*)target) [2] == 0);
3693 #endif
3694                 /* Empty */
3695         } else if (!no_ftnptr) {
3696 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3697                 g_assert (((gpointer*)target) [2] != 0);
3698 #endif
3699                 target = mono_create_ftnptr (mono_domain_get (), target);
3700         }
3701
3702         mono_mempool_destroy (mp);
3703
3704         /* Patch the PLT entry with target which might be the actual method not a trampoline */
3705         plt_entry = mono_aot_get_plt_entry (code);
3706         g_assert (plt_entry);
3707         mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target);
3708
3709         return target;
3710 #else
3711         g_assert_not_reached ();
3712         return NULL;
3713 #endif
3714 }
3715
3716 /**
3717  * init_plt:
3718  *
3719  *   Initialize the PLT table of the AOT module. Called lazily when the first AOT
3720  * method in the module is loaded to avoid committing memory by writing to it.
3721  * LOCKING: Assumes the AOT lock is held.
3722  */
3723 static void
3724 init_plt (MonoAotModule *amodule)
3725 {
3726         int i;
3727         gpointer tramp;
3728
3729         if (amodule->plt_inited)
3730                 return;
3731
3732         tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
3733
3734         /*
3735          * Initialize the PLT entries in the GOT to point to the default targets.
3736          */
3737
3738         tramp = mono_create_ftnptr (mono_domain_get (), tramp);
3739          for (i = 1; i < amodule->info.plt_size; ++i)
3740                  /* All the default entries point to the AOT trampoline */
3741                  ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
3742
3743         amodule->plt_inited = TRUE;
3744 }
3745
3746 /*
3747  * mono_aot_get_plt_entry:
3748  *
3749  *   Return the address of the PLT entry called by the code at CODE if exists.
3750  */
3751 guint8*
3752 mono_aot_get_plt_entry (guint8 *code)
3753 {
3754         MonoAotModule *amodule = find_aot_module (code);
3755         guint8 *target = NULL;
3756
3757         if (!amodule)
3758                 return NULL;
3759
3760 #ifdef TARGET_ARM
3761         if (amodule->thumb_end && code < amodule->thumb_end) {
3762                 return mono_arm_get_thumb_plt_entry (code);
3763         }
3764 #endif
3765
3766 #ifdef MONO_ARCH_AOT_SUPPORTED
3767         target = mono_arch_get_call_target (code);
3768 #else
3769         g_assert_not_reached ();
3770 #endif
3771
3772 #ifdef MONOTOUCH
3773         while (target != NULL) {
3774                 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
3775                         return target;
3776                 
3777                 // Add 4 since mono_arch_get_call_target assumes we're passing
3778                 // the instruction after the actual branch instruction.
3779                 target = mono_arch_get_call_target (target + 4);
3780         }
3781
3782         return NULL;
3783 #else
3784         if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
3785                 return target;
3786         else
3787                 return NULL;
3788 #endif
3789 }
3790
3791 /*
3792  * mono_aot_get_plt_info_offset:
3793  *
3794  *   Return the PLT info offset belonging to the plt entry called by CODE.
3795  */
3796 guint32
3797 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3798 {
3799         guint8 *plt_entry = mono_aot_get_plt_entry (code);
3800
3801         g_assert (plt_entry);
3802
3803         /* The offset is embedded inside the code after the plt entry */
3804 #ifdef MONO_ARCH_AOT_SUPPORTED
3805         return mono_arch_get_plt_info_offset (plt_entry, regs, code);
3806 #else
3807         g_assert_not_reached ();
3808         return 0;
3809 #endif
3810 }
3811
3812 static gpointer
3813 mono_create_ftnptr_malloc (guint8 *code)
3814 {
3815 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3816         MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
3817
3818         ftnptr->code = code;
3819         ftnptr->toc = NULL;
3820         ftnptr->env = NULL;
3821
3822         return ftnptr;
3823 #else
3824         return code;
3825 #endif
3826 }
3827
3828 /*
3829  * mono_aot_register_jit_icall:
3830  *
3831  *   Register a JIT icall which is called by trampolines in full-aot mode. This should
3832  * be called from mono_arch_init () during startup.
3833  */
3834 void
3835 mono_aot_register_jit_icall (const char *name, gpointer addr)
3836 {
3837         /* No need for locking */
3838         if (!aot_jit_icall_hash)
3839                 aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
3840         g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
3841 }
3842
3843 /*
3844  * load_function_full:
3845  *
3846  *   Load the function named NAME from the aot image. 
3847  */
3848 static gpointer
3849 load_function_full (MonoAotModule *amodule, const char *name, MonoTrampInfo **out_tinfo)
3850 {
3851         char *symbol;
3852         guint8 *p;
3853         int n_patches, pindex;
3854         MonoMemPool *mp;
3855         gpointer code;
3856         guint32 info_offset;
3857
3858         /* Load the code */
3859
3860         symbol = g_strdup_printf ("%s", name);
3861         find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
3862         g_free (symbol);
3863         if (!code)
3864                 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
3865
3866         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.", name, amodule->aot_name);
3867
3868         /* Load info */
3869
3870         symbol = g_strdup_printf ("%s_p", name);
3871         find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
3872         g_free (symbol);
3873         if (!p)
3874                 /* Nothing to patch */
3875                 return code;
3876
3877         info_offset = *(guint32*)p;
3878         if (out_tinfo) {
3879                 MonoTrampInfo *tinfo;
3880                 guint32 code_size, uw_info_len, uw_offset;
3881                 guint8 *uw_info;
3882                 /* Construct a MonoTrampInfo from the data in the AOT image */
3883
3884                 p += sizeof (guint32);
3885                 code_size = *(guint32*)p;
3886                 p += sizeof (guint32);
3887                 uw_offset = *(guint32*)p;
3888                 uw_info = amodule->unwind_info + uw_offset;
3889                 uw_info_len = decode_value (uw_info, &uw_info);
3890
3891                 tinfo = g_new0 (MonoTrampInfo, 1);
3892                 tinfo->code = code;
3893                 tinfo->code_size = code_size;
3894                 tinfo->uw_info = uw_info;
3895                 tinfo->uw_info_len = uw_info_len;
3896
3897                 *out_tinfo = tinfo;
3898         }
3899
3900         p = amodule->blob + info_offset;
3901
3902         /* Similar to mono_aot_load_method () */
3903
3904         n_patches = decode_value (p, &p);
3905
3906         if (n_patches) {
3907                 MonoJumpInfo *patches;
3908                 guint32 *got_slots;
3909
3910                 mp = mono_mempool_new ();
3911
3912                 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3913                 g_assert (patches);
3914
3915                 for (pindex = 0; pindex < n_patches; ++pindex) {
3916                         MonoJumpInfo *ji = &patches [pindex];
3917                         gpointer target;
3918
3919                         if (amodule->got [got_slots [pindex]])
3920                                 continue;
3921
3922                         /*
3923                          * When this code is executed, the runtime may not be initalized yet, so
3924                          * resolve the patch info by hand.
3925                          */
3926                         if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
3927                                 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
3928                                         target = mono_get_lmf_addr;
3929                                 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
3930                                         target = mono_thread_force_interruption_checkpoint;
3931                                 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
3932                                         target = mono_exception_from_token;
3933                                 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
3934                                         target = mono_get_throw_exception ();
3935                                 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
3936                                         int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
3937                                         target = (gpointer)mono_get_trampoline_func (tramp_type2);
3938                                 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
3939                                         /* atoll is needed because the the offset is unsigned */
3940                                         guint32 slot;
3941                                         int res;
3942
3943                                         res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
3944                                         g_assert (res == 1);
3945                                         target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
3946                                         target = mono_create_ftnptr_malloc (target);
3947                                 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
3948                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
3949                                         target = mono_create_ftnptr_malloc (target);
3950                                 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
3951                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
3952                                         target = mono_create_ftnptr_malloc (target);
3953                                 } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
3954                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
3955                                         target = mono_create_ftnptr_malloc (target);
3956                                 } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
3957                                         target = mono_thread_get_and_clear_pending_exception;
3958                                 } else if (strstr (ji->data.name, "generic_trampoline_")) {
3959                                         target = mono_aot_get_trampoline (ji->data.name);
3960                                 } else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
3961                                         /* Registered by mono_arch_init () */
3962                                         target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
3963                                 } else {
3964                                         fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
3965                                         g_assert_not_reached ();
3966                                         target = NULL;
3967                                 }
3968                         } else {
3969                                 /* Hopefully the code doesn't have patches which need method or 
3970                                  * domain to be set.
3971                                  */
3972                                 target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
3973                                 g_assert (target);
3974                         }
3975
3976                         amodule->got [got_slots [pindex]] = target;
3977                 }
3978
3979                 g_free (got_slots);
3980
3981                 mono_mempool_destroy (mp);
3982         }
3983
3984         return code;
3985 }
3986
3987 static gpointer
3988 load_function (MonoAotModule *amodule, const char *name)
3989 {
3990         return load_function_full (amodule, name, NULL);
3991 }
3992
3993 /*
3994  * Return the trampoline identified by NAME from the mscorlib AOT file.
3995  * On ppc64, this returns a function descriptor.
3996  */
3997 gpointer
3998 mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
3999 {
4000         MonoImage *image;
4001         MonoAotModule *amodule;
4002
4003         image = mono_defaults.corlib;
4004         g_assert (image);
4005
4006         amodule = image->aot_module;
4007         g_assert (amodule);
4008
4009         return mono_create_ftnptr_malloc (load_function_full (amodule, name, out_tinfo));
4010 }
4011
4012 gpointer
4013 mono_aot_get_trampoline (const char *name)
4014 {
4015         return mono_aot_get_trampoline_full (name, NULL);
4016 }
4017
4018 #ifdef MONOTOUCH
4019 #include <mach/mach.h>
4020
4021 static TrampolinePage* trampoline_pages [MONO_AOT_TRAMP_NUM];
4022 /* these sizes are for ARM code, parametrize if porting to other architectures (see arch_emit_specific_trampoline_pages)
4023  * trampoline size is assumed to be 8 bytes below as well (8 is the minimum for 32 bit archs, since we need to store
4024  * two pointers for trampoline in the data page).
4025  * the minimum for the common code must be at least sizeof(TrampolinePage), since we store the page info at the
4026  * beginning of the data page.
4027  */
4028 static const int trampolines_pages_code_offsets [MONO_AOT_TRAMP_NUM] = {16, 16, 72, 16};
4029
4030 static unsigned char*
4031 get_new_trampoline_from_page (int tramp_type)
4032 {
4033         MonoAotModule *amodule;
4034         MonoImage *image;
4035         TrampolinePage *page;
4036         int count;
4037         void *tpage;
4038         vm_address_t addr, taddr;
4039         kern_return_t ret;
4040         vm_prot_t prot, max_prot;
4041         int psize;
4042         unsigned char *code;
4043
4044         mono_aot_page_lock ();
4045         page = trampoline_pages [tramp_type];
4046         if (page && page->trampolines < page->trampolines_end) {
4047                 code = page->trampolines;
4048                 page->trampolines += 8;
4049                 mono_aot_page_unlock ();
4050                 return code;
4051         }
4052         mono_aot_page_unlock ();
4053         psize = mono_pagesize ();
4054         /* the trampoline template page is in the mscorlib module */
4055         image = mono_defaults.corlib;
4056         g_assert (image);
4057
4058         amodule = image->aot_module;
4059         g_assert (amodule);
4060
4061         if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
4062                 tpage = load_function (amodule, "specific_trampolines_page");
4063         else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
4064                 tpage = load_function (amodule, "rgctx_trampolines_page");
4065         else if (tramp_type == MONO_AOT_TRAMP_IMT_THUNK)
4066                 tpage = load_function (amodule, "imt_trampolines_page");
4067         else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
4068                 tpage = load_function (amodule, "gsharedvt_arg_trampolines_page");
4069         else
4070                 g_error ("Incorrect tramp type for trampolines page");
4071         g_assert (tpage);
4072         /*g_warning ("loaded trampolines page at %x", tpage);*/
4073
4074         /* avoid the unlikely case of looping forever */
4075         count = 40;
4076         page = NULL;
4077         while (page == NULL && count-- > 0) {
4078                 addr = 0;
4079                 /* allocate two contiguous pages of memory: the first page will contain the data (like a local constant pool)
4080                  * while the second will contain the trampolines.
4081                  */
4082                 ret = vm_allocate (mach_task_self (), &addr, psize * 2, VM_FLAGS_ANYWHERE);
4083                 if (ret != KERN_SUCCESS) {
4084                         g_error ("Cannot allocate memory for trampolines: %d", ret);
4085                         break;
4086                 }
4087                 /*g_warning ("allocated trampoline double page at %x", addr);*/
4088                 /* replace the second page with a remapped trampoline page */
4089                 taddr = addr + psize;
4090                 vm_deallocate (mach_task_self (), taddr, psize);
4091                 ret = vm_remap (mach_task_self (), &taddr, psize, 0, FALSE, mach_task_self(), (vm_address_t)tpage, FALSE, &prot, &max_prot, VM_INHERIT_SHARE);
4092                 if (ret != KERN_SUCCESS) {
4093                         /* someone else got the page, try again  */
4094                         vm_deallocate (mach_task_self (), addr, psize);
4095                         continue;
4096                 }
4097                 /*g_warning ("remapped trampoline page at %x", taddr);*/
4098
4099                 mono_aot_page_lock ();
4100                 page = trampoline_pages [tramp_type];
4101                 /* some other thread already allocated, so use that to avoid wasting memory */
4102                 if (page && page->trampolines < page->trampolines_end) {
4103                         code = page->trampolines;
4104                         page->trampolines += 8;
4105                         mono_aot_page_unlock ();
4106                         vm_deallocate (mach_task_self (), addr, psize);
4107                         vm_deallocate (mach_task_self (), taddr, psize);
4108                         return code;
4109                 }
4110                 page = (TrampolinePage*)addr;
4111                 page->next = trampoline_pages [tramp_type];
4112                 trampoline_pages [tramp_type] = page;
4113                 page->trampolines = (void*)(taddr + trampolines_pages_code_offsets [tramp_type]);
4114                 page->trampolines_end = (void*)(taddr + psize);
4115                 code = page->trampolines;
4116                 page->trampolines += 8;
4117                 mono_aot_page_unlock ();
4118                 return code;
4119         }
4120         g_error ("Cannot allocate more trampoline pages: %d", ret);
4121         return NULL;
4122 }
4123
4124 #else
4125 static unsigned char*
4126 get_new_trampoline_from_page (int tramp_type)
4127 {
4128         g_error ("Page trampolines not supported.");
4129         return NULL;
4130 }
4131 #endif
4132
4133
4134 static gpointer
4135 get_new_specific_trampoline_from_page (gpointer tramp, gpointer arg)
4136 {
4137         void *code;
4138         gpointer *data;
4139
4140         code = get_new_trampoline_from_page (MONO_AOT_TRAMP_SPECIFIC);
4141
4142         data = (gpointer*)((char*)code - mono_pagesize ());
4143         data [0] = arg;
4144         data [1] = tramp;
4145         /*g_warning ("new trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4146         return code;
4147
4148 }
4149
4150 static gpointer
4151 get_new_rgctx_trampoline_from_page (gpointer tramp, gpointer arg)
4152 {
4153         void *code;
4154         gpointer *data;
4155
4156         code = get_new_trampoline_from_page (MONO_AOT_TRAMP_STATIC_RGCTX);
4157
4158         data = (gpointer*)((char*)code - mono_pagesize ());
4159         data [0] = arg;
4160         data [1] = tramp;
4161         /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4162         return code;
4163
4164 }
4165
4166 static gpointer
4167 get_new_imt_trampoline_from_page (gpointer arg)
4168 {
4169         void *code;
4170         gpointer *data;
4171
4172         code = get_new_trampoline_from_page (MONO_AOT_TRAMP_IMT_THUNK);
4173
4174         data = (gpointer*)((char*)code - mono_pagesize ());
4175         data [0] = arg;
4176         /*g_warning ("new imt trampoline at %p for data %p, (stored at %p)", code, arg, data);*/
4177         return code;
4178
4179 }
4180
4181 static gpointer
4182 get_new_gsharedvt_arg_trampoline_from_page (gpointer tramp, gpointer arg)
4183 {
4184         void *code;
4185         gpointer *data;
4186
4187         code = get_new_trampoline_from_page (MONO_AOT_TRAMP_GSHAREDVT_ARG);
4188
4189         data = (gpointer*)((char*)code - mono_pagesize ());
4190         data [0] = arg;
4191         data [1] = tramp;
4192         /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4193         return code;
4194 }
4195
4196 /* Return a given kind of trampoline */
4197 static gpointer
4198 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
4199 {
4200         MonoAotModule *amodule;
4201         int index, tramp_size;
4202         MonoImage *image;
4203
4204         /* Currently, we keep all trampolines in the mscorlib AOT image */
4205         image = mono_defaults.corlib;
4206         g_assert (image);
4207
4208         mono_aot_lock ();
4209
4210         amodule = image->aot_module;
4211         g_assert (amodule);
4212
4213         *out_amodule = amodule;
4214
4215 #ifdef MONOTOUCH
4216 #define MONOTOUCH_TRAMPOLINES_ERROR ". See http://docs.xamarin.com/ios/troubleshooting for instruction on how to fix this condition"
4217 #else
4218 #define MONOTOUCH_TRAMPOLINES_ERROR ""
4219 #endif
4220         if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type]) {
4221                 g_error ("Ran out of trampolines of type %d in '%s' (%d)%s\n", 
4222                                  tramp_type, image->name, amodule->info.num_trampolines [tramp_type], MONOTOUCH_TRAMPOLINES_ERROR);
4223         }
4224         index = amodule->trampoline_index [tramp_type] ++;
4225
4226         mono_aot_unlock ();
4227
4228         *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
4229
4230         tramp_size = amodule->info.trampoline_size [tramp_type];
4231
4232         if (out_tramp_size)
4233                 *out_tramp_size = tramp_size;
4234
4235         return amodule->trampolines [tramp_type] + (index * tramp_size);
4236 }
4237
4238 /*
4239  * Return a specific trampoline from the AOT file.
4240  */
4241 gpointer
4242 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
4243 {
4244         MonoAotModule *amodule;
4245         guint32 got_offset, tramp_size;
4246         guint8 *code, *tramp;
4247         static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
4248         static gboolean inited;
4249         static guint32 num_trampolines;
4250
4251         if (!inited) {
4252                 mono_aot_lock ();
4253
4254                 if (!inited) {
4255                         mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
4256                         inited = TRUE;
4257                 }
4258
4259                 mono_aot_unlock ();
4260         }
4261
4262         num_trampolines ++;
4263
4264         if (!generic_trampolines [tramp_type]) {
4265                 char *symbol;
4266
4267                 symbol = mono_get_generic_trampoline_name (tramp_type);
4268                 generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
4269                 g_free (symbol);
4270         }
4271
4272         tramp = generic_trampolines [tramp_type];
4273         g_assert (tramp);
4274
4275         if (USE_PAGE_TRAMPOLINES) {
4276                 code = get_new_specific_trampoline_from_page (tramp, arg1);
4277                 tramp_size = 8;
4278         } else {
4279                 code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
4280
4281                 amodule->got [got_offset] = tramp;
4282                 amodule->got [got_offset + 1] = arg1;
4283         }
4284
4285         if (code_len)
4286                 *code_len = tramp_size;
4287
4288         return code;
4289 }
4290
4291 gpointer
4292 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
4293 {
4294         MonoAotModule *amodule;
4295         guint8 *code;
4296         guint32 got_offset;
4297
4298         if (USE_PAGE_TRAMPOLINES) {
4299                 code = get_new_rgctx_trampoline_from_page (addr, ctx);
4300         } else {
4301                 code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
4302
4303                 amodule->got [got_offset] = ctx;
4304                 amodule->got [got_offset + 1] = addr; 
4305         }
4306
4307         /* The caller expects an ftnptr */
4308         return mono_create_ftnptr (mono_domain_get (), code);
4309 }
4310
4311 gpointer
4312 mono_aot_get_unbox_trampoline (MonoMethod *method)
4313 {
4314         guint32 method_index = mono_metadata_token_index (method->token) - 1;
4315         MonoAotModule *amodule;
4316         gpointer code;
4317         guint32 *ut, *ut_end, *entry;
4318         int low, high, entry_index;
4319
4320         if (method->is_inflated && !mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE, FALSE)) {
4321                 method_index = find_extra_method (method, &amodule);
4322                 if (method_index == 0xffffff && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE, TRUE)) {
4323                         MonoMethod *shared = mini_get_shared_method_full (method, TRUE, TRUE);
4324                         method_index = find_extra_method (shared, &amodule);
4325                 }
4326                 g_assert (method_index != 0xffffff);
4327         } else {
4328                 amodule = method->klass->image->aot_module;
4329                 g_assert (amodule);
4330         }
4331
4332         ut = amodule->unbox_trampolines;
4333         ut_end = amodule->unbox_trampolines_end;
4334
4335         /* Do a binary search in the sorted table */
4336         code = NULL;
4337         low = 0;
4338         high = (ut_end - ut) / 2;
4339         while (low < high) {
4340                 entry_index = (low + high) / 2;
4341                 entry = &ut [(entry_index * 2)];
4342                 if (entry [0] < method_index) {
4343                         low = entry_index + 1;
4344                 } else if (entry [0] > method_index) {
4345                         high = entry_index;
4346                 } else {
4347                         if (amodule->info.flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES)
4348                                 code = (gpointer)(gsize)entry [1];
4349                         else
4350                                 code = amodule->code + entry [1];
4351                         break;
4352                 }
4353         }
4354         g_assert (code);
4355
4356         /* The caller expects an ftnptr */
4357         return mono_create_ftnptr (mono_domain_get (), code);
4358 }
4359
4360 gpointer
4361 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
4362 {
4363         char *symbol;
4364         gpointer code;
4365         MonoAotModule *amodule = mono_defaults.corlib->aot_module;
4366         guint32 index = MONO_RGCTX_SLOT_INDEX (slot);
4367         static int count = 0;
4368
4369         count ++;
4370         if (index >= amodule->info.num_rgctx_fetch_trampolines) {
4371                 static gpointer addr;
4372                 gpointer *info;
4373
4374                 /*
4375                  * Use the general version of the rgctx fetch trampoline. It receives a pair of <slot, trampoline> in the rgctx arg reg.
4376                  */
4377                 if (!addr)
4378                         addr = load_function (amodule, "rgctx_fetch_trampoline_general");
4379                 info = mono_domain_alloc0 (mono_get_root_domain (), sizeof (gpointer) * 2);
4380                 info [0] = GUINT_TO_POINTER (slot);
4381                 info [1] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
4382                 code = mono_aot_get_static_rgctx_trampoline (info, addr);
4383                 return mono_create_ftnptr (mono_domain_get (), code);
4384         }
4385
4386         symbol = mono_get_rgctx_fetch_trampoline_name (slot);
4387         code = load_function (mono_defaults.corlib->aot_module, symbol);
4388         g_free (symbol);
4389         /* The caller expects an ftnptr */
4390         return mono_create_ftnptr (mono_domain_get (), code);
4391 }
4392
4393 gpointer
4394 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
4395 {
4396         guint32 got_offset;
4397         gpointer code;
4398         gpointer *buf;
4399         int i, index, real_count;
4400         MonoAotModule *amodule;
4401
4402         real_count = 0;
4403         for (i = 0; i < count; ++i) {
4404                 MonoIMTCheckItem *item = imt_entries [i];
4405
4406                 if (item->is_equals)
4407                         real_count ++;
4408         }
4409
4410         /* Save the entries into an array */
4411         buf = mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
4412         index = 0;
4413         for (i = 0; i < count; ++i) {
4414                 MonoIMTCheckItem *item = imt_entries [i];               
4415
4416                 if (!item->is_equals)
4417                         continue;
4418
4419                 g_assert (item->key);
4420
4421                 buf [(index * 2)] = item->key;
4422                 if (item->has_target_code) {
4423                         gpointer *p = mono_domain_alloc (domain, sizeof (gpointer));
4424                         *p = item->value.target_code;
4425                         buf [(index * 2) + 1] = p;
4426                 } else {
4427                         buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
4428                 }
4429                 index ++;
4430         }
4431         buf [(index * 2)] = NULL;
4432         buf [(index * 2) + 1] = fail_tramp;
4433         
4434         if (USE_PAGE_TRAMPOLINES) {
4435                 code = get_new_imt_trampoline_from_page (buf);
4436         } else {
4437                 code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
4438
4439                 amodule->got [got_offset] = buf;
4440         }
4441
4442         return code;
4443 }
4444
4445 gpointer
4446 mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
4447 {
4448         MonoAotModule *amodule;
4449         guint8 *code;
4450         guint32 got_offset;
4451
4452         if (USE_PAGE_TRAMPOLINES) {
4453                 code = get_new_gsharedvt_arg_trampoline_from_page (addr, arg);
4454         } else {
4455                 code = get_numerous_trampoline (MONO_AOT_TRAMP_GSHAREDVT_ARG, 2, &amodule, &got_offset, NULL);
4456
4457                 amodule->got [got_offset] = arg;
4458                 amodule->got [got_offset + 1] = addr; 
4459         }
4460
4461         /* The caller expects an ftnptr */
4462         return mono_create_ftnptr (mono_domain_get (), code);
4463 }
4464  
4465 /*
4466  * mono_aot_set_make_unreadable:
4467  *
4468  *   Set whenever to make all mmaped memory unreadable. In conjuction with a
4469  * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
4470  */
4471 void
4472 mono_aot_set_make_unreadable (gboolean unreadable)
4473 {
4474         static int inited;
4475
4476         make_unreadable = unreadable;
4477
4478         if (make_unreadable && !inited) {
4479                 mono_counters_register ("AOT pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
4480         }               
4481 }
4482
4483 typedef struct {
4484         MonoAotModule *module;
4485         guint8 *ptr;
4486 } FindMapUserData;
4487
4488 static void
4489 find_map (gpointer key, gpointer value, gpointer user_data)
4490 {
4491         MonoAotModule *module = (MonoAotModule*)value;
4492         FindMapUserData *data = (FindMapUserData*)user_data;
4493
4494         if (!data->module)
4495                 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
4496                         data->module = module;
4497 }
4498
4499 static MonoAotModule*
4500 find_module_for_addr (void *ptr)
4501 {
4502         FindMapUserData data;
4503
4504         if (!make_unreadable)
4505                 return NULL;
4506
4507         data.module = NULL;
4508         data.ptr = (guint8*)ptr;
4509
4510         mono_aot_lock ();
4511         g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
4512         mono_aot_unlock ();
4513
4514         return data.module;
4515 }
4516
4517 /*
4518  * mono_aot_is_pagefault:
4519  *
4520  *   Should be called from a SIGSEGV signal handler to find out whenever @ptr is
4521  * within memory allocated by this module.
4522  */
4523 gboolean
4524 mono_aot_is_pagefault (void *ptr)
4525 {
4526         if (!make_unreadable)
4527                 return FALSE;
4528
4529         /* 
4530          * Not signal safe, but SIGSEGV's are synchronous, and
4531          * this is only turned on by a MONO_DEBUG option.
4532          */
4533         return find_module_for_addr (ptr) != NULL;
4534 }
4535
4536 /*
4537  * mono_aot_handle_pagefault:
4538  *
4539  *   Handle a pagefault caused by an unreadable page by making it readable again.
4540  */
4541 void
4542 mono_aot_handle_pagefault (void *ptr)
4543 {
4544 #ifndef PLATFORM_WIN32
4545         guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
4546         int res;
4547
4548         mono_aot_lock ();
4549         res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
4550         g_assert (res == 0);
4551
4552         n_pagefaults ++;
4553         mono_aot_unlock ();
4554 #endif
4555 }
4556
4557 #else
4558 /* AOT disabled */
4559
4560 void
4561 mono_aot_init (void)
4562 {
4563 }
4564
4565 gpointer
4566 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
4567 {
4568         return NULL;
4569 }
4570
4571 gboolean
4572 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
4573 {
4574         return FALSE;
4575 }
4576
4577 gboolean
4578 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
4579 {
4580         return FALSE;
4581 }
4582
4583 gboolean
4584 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
4585 {
4586         return FALSE;
4587 }
4588
4589 MonoJitInfo *
4590 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
4591 {
4592         return NULL;
4593 }
4594
4595 gpointer
4596 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
4597 {
4598         return NULL;
4599 }
4600
4601 guint8*
4602 mono_aot_get_plt_entry (guint8 *code)
4603 {
4604         return NULL;
4605 }
4606
4607 gpointer
4608 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
4609 {
4610         return NULL;
4611 }
4612
4613 void
4614 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
4615 {
4616 }
4617
4618 gpointer
4619 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
4620 {
4621         return NULL;
4622 }
4623
4624 guint32
4625 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
4626 {
4627         g_assert_not_reached ();
4628
4629         return 0;
4630 }
4631
4632 gpointer
4633 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
4634 {
4635         g_assert_not_reached ();
4636         return NULL;
4637 }
4638
4639 gpointer
4640 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
4641 {
4642         g_assert_not_reached ();
4643         return NULL;
4644 }
4645
4646 gpointer
4647 mono_aot_get_trampoline (const char *name)
4648 {
4649         g_assert_not_reached ();
4650         return NULL;
4651 }
4652
4653 gpointer
4654 mono_aot_get_unbox_trampoline (MonoMethod *method)
4655 {
4656         g_assert_not_reached ();
4657         return NULL;
4658 }
4659
4660 gpointer
4661 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
4662 {
4663         g_assert_not_reached ();
4664         return NULL;
4665 }
4666
4667 gpointer
4668 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
4669 {
4670         g_assert_not_reached ();
4671         return NULL;
4672 }       
4673
4674 guint8*
4675 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
4676 {
4677         g_assert_not_reached ();
4678         return NULL;
4679 }
4680
4681 void
4682 mono_aot_register_jit_icall (const char *name, gpointer addr)
4683 {
4684 }
4685
4686 #endif