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