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