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