Get rid of all references to STATIC_RGCTX_INVOKE to fix the build.
[mono.git] / mono / mini / aot-compiler.c
1 /*
2  * aot-compiler.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 /* Remaining AOT-only work:
12  * - reduce the length of the wrapper names.
13  * - aot IMT tables, so we don't have two kinds of aot code.
14  * - optimize the trampolines, generate more code in the arch files.
15  * - make things more consistent with how elf works, for example, use ELF 
16  *   relocations.
17  * Remaining generics sharing work:
18  * - optimize the size of the data which is encoded.
19  * - optimize the runtime loading of data:
20  *   - the trampoline code calls mono_jit_info_table_find () to find the rgctx, 
21  *     which loads the debugging+exception handling info for the method. This is a 
22  *     huge waste of time and code, since the rgctx structure is currently empty.
23  *   - every shared method has a MonoGenericJitInfo structure which is only really
24  *     used for handling catch clauses with open types, not a very common use case.
25  */
26
27 #include "config.h"
28 #include <sys/types.h>
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32 #ifdef HAVE_STDINT_H
33 #include <stdint.h>
34 #endif
35 #include <fcntl.h>
36 #include <ctype.h>
37 #include <string.h>
38 #ifndef PLATFORM_WIN32
39 #include <sys/time.h>
40 #else
41 #include <winsock2.h>
42 #include <windows.h>
43 #endif
44
45 #include <errno.h>
46 #include <sys/stat.h>
47
48 #include <mono/metadata/tabledefs.h>
49 #include <mono/metadata/class.h>
50 #include <mono/metadata/object.h>
51 #include <mono/metadata/tokentype.h>
52 #include <mono/metadata/appdomain.h>
53 #include <mono/metadata/debug-helpers.h>
54 #include <mono/metadata/assembly.h>
55 #include <mono/metadata/metadata-internals.h>
56 #include <mono/metadata/marshal.h>
57 #include <mono/metadata/gc-internal.h>
58 #include <mono/metadata/monitor.h>
59 #include <mono/metadata/mempool-internals.h>
60 #include <mono/metadata/mono-endian.h>
61 #include <mono/metadata/threads-types.h>
62 #include <mono/utils/mono-logger.h>
63 #include <mono/utils/mono-compiler.h>
64 #include <mono/utils/mono-time.h>
65 #include <mono/utils/mono-mmap.h>
66
67 #include "mini.h"
68 #include "image-writer.h"
69 #include "dwarfwriter.h"
70
71 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
72
73 #define TV_DECLARE(name) gint64 name
74 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
75 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
76
77 #ifdef PLATFORM_WIN32
78 #define SHARED_EXT ".dll"
79 #elif defined(__ppc__) && defined(__MACH__)
80 #define SHARED_EXT ".dylib"
81 #else
82 #define SHARED_EXT ".so"
83 #endif
84
85 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
86 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
87 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
88
89 typedef struct MonoAotOptions {
90         char *outfile;
91         gboolean save_temps;
92         gboolean write_symbols;
93         gboolean metadata_only;
94         gboolean bind_to_runtime_version;
95         gboolean full_aot;
96         gboolean no_dlsym;
97         gboolean static_link;
98         gboolean asm_only;
99         gboolean asm_writer;
100         gboolean nodebug;
101         int nthreads;
102         int ntrampolines;
103         gboolean print_skipped_methods;
104 } MonoAotOptions;
105
106 typedef struct MonoAotStats {
107         int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
108         int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
109         int methods_without_got_slots, direct_calls, all_calls;
110         int got_slots;
111         int got_slot_types [MONO_PATCH_INFO_NONE];
112         int jit_time, gen_time, link_time;
113 } MonoAotStats;
114
115 typedef struct MonoAotCompile {
116         MonoImage *image;
117         GPtrArray *methods;
118         GHashTable *method_indexes;
119         MonoCompile **cfgs;
120         int cfgs_size;
121         GHashTable *patch_to_plt_offset;
122         GHashTable *plt_offset_to_patch;
123         GHashTable *patch_to_got_offset;
124         GPtrArray *got_patches;
125         GHashTable *image_hash;
126         GHashTable *method_to_cfg;
127         GHashTable *token_info_hash;
128         GPtrArray *extra_methods;
129         GPtrArray *image_table;
130         GPtrArray *globals;
131         GList *method_order;
132         guint32 *plt_got_info_offsets;
133         guint32 got_offset, plt_offset, plt_got_offset_base;
134         /* Number of GOT entries reserved for trampolines */
135         guint32 num_trampoline_got_entries;
136
137         guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
138         guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
139         guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
140
141         MonoAotOptions aot_opts;
142         guint32 nmethods;
143         guint32 opts;
144         MonoMemPool *mempool;
145         MonoAotStats stats;
146         int method_index;
147         char *static_linking_symbol;
148         CRITICAL_SECTION mutex;
149         gboolean use_bin_writer;
150         MonoImageWriter *w;
151         MonoDwarfWriter *dwarf;
152         FILE *fp;
153         char *tmpfname;
154         GSList *cie_program;
155         GHashTable *unwind_info_offsets;
156         GPtrArray *unwind_ops;
157         guint32 unwind_info_offset;
158         char *got_symbol;
159         GHashTable *method_label_hash;
160 } MonoAotCompile;
161
162 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
163 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
164
165 #ifdef HAVE_ARRAY_ELEM_INIT
166 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
167 #define MSGSTRFIELD1(line) str##line
168 static const struct msgstr_t {
169 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
170 #include "patch-info.h"
171 #undef PATCH_INFO
172 } opstr = {
173 #define PATCH_INFO(a,b) b,
174 #include "patch-info.h"
175 #undef PATCH_INFO
176 };
177 static const gint16 opidx [] = {
178 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
179 #include "patch-info.h"
180 #undef PATCH_INFO
181 };
182
183 static G_GNUC_UNUSED const char*
184 get_patch_name (int info)
185 {
186         return (const char*)&opstr + opidx [info];
187 }
188
189 #else
190 #define PATCH_INFO(a,b) b,
191 static const char* const
192 patch_types [MONO_PATCH_INFO_NUM + 1] = {
193 #include "patch-info.h"
194         NULL
195 };
196
197 static const char*
198 get_patch_name (int info)
199 {
200         return patch_types [info];
201 }
202
203 #endif
204
205 /* Wrappers around the image writer functions */
206
207 static inline void
208 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
209 {
210         img_writer_emit_section_change (acfg->w, section_name, subsection_index);
211 }
212
213 static inline void
214 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
215 {
216         img_writer_emit_push_section (acfg->w, section_name, subsection);
217 }
218
219 static inline void
220 emit_pop_section (MonoAotCompile *acfg)
221 {
222         img_writer_emit_pop_section (acfg->w);
223 }
224
225 static inline void
226 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func) 
227
228         img_writer_emit_local_symbol (acfg->w, name, end_label, func); 
229 }
230
231 static inline void
232 emit_label (MonoAotCompile *acfg, const char *name) 
233
234         img_writer_emit_label (acfg->w, name); 
235 }
236
237 static inline void
238 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size) 
239
240         img_writer_emit_bytes (acfg->w, buf, size); 
241 }
242
243 static inline void
244 emit_string (MonoAotCompile *acfg, const char *value) 
245
246         img_writer_emit_string (acfg->w, value); 
247 }
248
249 static inline void
250 emit_line (MonoAotCompile *acfg) 
251
252         img_writer_emit_line (acfg->w); 
253 }
254
255 static inline void
256 emit_alignment (MonoAotCompile *acfg, int size) 
257
258         img_writer_emit_alignment (acfg->w, size); 
259 }
260
261 static inline void
262 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target) 
263
264         img_writer_emit_pointer_unaligned (acfg->w, target); 
265 }
266
267 static inline void
268 emit_pointer (MonoAotCompile *acfg, const char *target) 
269
270         img_writer_emit_pointer (acfg->w, target); 
271 }
272
273 static inline void
274 emit_int16 (MonoAotCompile *acfg, int value) 
275
276         img_writer_emit_int16 (acfg->w, value); 
277 }
278
279 static inline void
280 emit_int32 (MonoAotCompile *acfg, int value) 
281
282         img_writer_emit_int32 (acfg->w, value); 
283 }
284
285 static inline void
286 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset) 
287
288         img_writer_emit_symbol_diff (acfg->w, end, start, offset); 
289 }
290
291 static inline void
292 emit_zero_bytes (MonoAotCompile *acfg, int num) 
293
294         img_writer_emit_zero_bytes (acfg->w, num); 
295 }
296
297 static inline void
298 emit_byte (MonoAotCompile *acfg, guint8 val) 
299
300         img_writer_emit_byte (acfg->w, val); 
301 }
302
303 static G_GNUC_UNUSED void
304 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
305 {
306         img_writer_emit_global (acfg->w, name, func);
307 }
308
309 static void
310 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
311 {
312         if (acfg->aot_opts.no_dlsym) {
313                 g_ptr_array_add (acfg->globals, g_strdup (name));
314         } else {
315                 img_writer_emit_global (acfg->w, name, func);
316         }
317 }
318
319 static void
320 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
321 {
322         img_writer_emit_section_change (acfg->w, ".text", 1);
323         emit_global (acfg, name, FALSE);
324         img_writer_emit_label (acfg->w, name);
325         img_writer_emit_string (acfg->w, value);
326 }
327
328 static G_GNUC_UNUSED void
329 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
330 {
331         do {
332                 guint8 b = value & 0x7f;
333                 value >>= 7;
334                 if (value != 0) /* more bytes to come */
335                         b |= 0x80;
336                 emit_byte (acfg, b);
337         } while (value);
338 }
339
340 static G_GNUC_UNUSED void
341 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
342 {
343         gboolean more = 1;
344         gboolean negative = (value < 0);
345         guint32 size = 64;
346         guint8 byte;
347
348         while (more) {
349                 byte = value & 0x7f;
350                 value >>= 7;
351                 /* the following is unnecessary if the
352                  * implementation of >>= uses an arithmetic rather
353                  * than logical shift for a signed left operand
354                  */
355                 if (negative)
356                         /* sign extend */
357                         value |= - ((gint64)1 <<(size - 7));
358                 /* sign bit of byte is second high order bit (0x40) */
359                 if ((value == 0 && !(byte & 0x40)) ||
360                         (value == -1 && (byte & 0x40)))
361                         more = 0;
362                 else
363                         byte |= 0x80;
364                 emit_byte (acfg, byte);
365         }
366 }
367
368 static G_GNUC_UNUSED void
369 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
370 {
371         guint8 *p = buf;
372
373         do {
374                 guint8 b = value & 0x7f;
375                 value >>= 7;
376                 if (value != 0) /* more bytes to come */
377                         b |= 0x80;
378                 *p ++ = b;
379         } while (value);
380
381         *endbuf = p;
382 }
383
384 static G_GNUC_UNUSED void
385 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
386 {
387         gboolean more = 1;
388         gboolean negative = (value < 0);
389         guint32 size = 32;
390         guint8 byte;
391         guint8 *p = buf;
392
393         while (more) {
394                 byte = value & 0x7f;
395                 value >>= 7;
396                 /* the following is unnecessary if the
397                  * implementation of >>= uses an arithmetic rather
398                  * than logical shift for a signed left operand
399                  */
400                 if (negative)
401                         /* sign extend */
402                         value |= - (1 <<(size - 7));
403                 /* sign bit of byte is second high order bit (0x40) */
404                 if ((value == 0 && !(byte & 0x40)) ||
405                         (value == -1 && (byte & 0x40)))
406                         more = 0;
407                 else
408                         byte |= 0x80;
409                 *p ++= byte;
410         }
411
412         *endbuf = p;
413 }
414
415 /* ARCHITECTURE SPECIFIC CODE */
416
417 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM)
418 #define EMIT_DWARF_INFO 1
419 #endif
420
421 /*
422  * arch_emit_direct_call:
423  *
424  *   Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
425  * calling code.
426  */
427 static void
428 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
429 {
430 #if defined(TARGET_X86) || defined(TARGET_AMD64)
431         /* Need to make sure this is exactly 5 bytes long */
432         emit_byte (acfg, '\xe8');
433         emit_symbol_diff (acfg, target, ".", -4);
434         *call_size = 5;
435 #elif defined(TARGET_ARM)
436         if (acfg->use_bin_writer) {
437                 guint8 buf [4];
438                 guint8 *code;
439
440                 code = buf;
441                 ARM_BL (code, 0);
442
443                 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
444                 emit_bytes (acfg, buf, 4);
445         } else {
446                 img_writer_emit_unset_mode (acfg->w);
447                 fprintf (acfg->fp, "bl %s\n", target);
448         }
449         *call_size = 4;
450 #else
451         g_assert_not_reached ();
452 #endif
453 }
454
455 #ifdef MONO_ARCH_AOT_SUPPORTED
456 /*
457  * arch_emit_got_offset:
458  *
459  *   The memory pointed to by CODE should hold native code for computing the GOT
460  * address. Emit this code while patching it with the offset between code and
461  * the GOT. CODE_SIZE is set to the number of bytes emitted.
462  */
463 static void
464 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
465 {
466         guint32 offset = mono_arch_get_patch_offset (code);
467         emit_bytes (acfg, code, offset);
468         emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
469
470         *code_size = offset + 4;
471 }
472
473 /*
474  * arch_emit_got_access:
475  *
476  *   The memory pointed to by CODE should hold native code for loading a GOT
477  * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
478  * CODE_SIZE is set to the number of bytes emitted.
479  */
480 static void
481 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
482 {
483         /* Emit beginning of instruction */
484         emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
485
486         /* Emit the offset */
487 #ifdef TARGET_AMD64
488         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
489 #elif defined(TARGET_X86)
490         emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
491 #elif defined(TARGET_ARM)
492         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
493 #else
494         g_assert_not_reached ();
495 #endif
496
497         *code_size = mono_arch_get_patch_offset (code) + 4;
498 }
499
500 #endif
501
502 /*
503  * arch_emit_plt_entry:
504  *
505  *   Emit code for the PLT entry with index INDEX.
506  */
507 static void
508 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
509 {
510 #if defined(TARGET_X86)
511                 if (index == 0) {
512                         /* It is filled up during loading by the AOT loader. */
513                         emit_zero_bytes (acfg, 16);
514                 } else {
515                         /* Need to make sure this is 9 bytes long */
516                         emit_byte (acfg, '\xe9');
517                         emit_symbol_diff (acfg, "plt", ".", -4);
518                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
519                 }
520 #elif defined(TARGET_AMD64)
521                 /*
522                  * We can't emit jumps because they are 32 bits only so they can't be patched.
523                  * So we make indirect calls through GOT entries which are patched by the AOT 
524                  * loader to point to .Lpd entries. 
525                  * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
526                  */
527                 /* jmpq *<offset>(%rip) */
528                 emit_byte (acfg, '\xff');
529                 emit_byte (acfg, '\x25');
530                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
531                 /* Used by mono_aot_get_plt_info_offset */
532                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
533 #elif defined(TARGET_ARM)
534                 guint8 buf [256];
535                 guint8 *code;
536
537                 /* FIXME:
538                  * - optimize OP_AOTCONST implementation
539                  * - optimize the PLT entries
540                  * - optimize SWITCH AOT implementation
541                  * - implement IMT support
542                  */
543                 code = buf;
544                 if (acfg->use_bin_writer) {
545                         /* We only emit 1 relocation since we implement it ourselves anyway */
546                         img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
547                         /* FIXME: A 2 instruction encoding is sufficient in most cases */
548                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
549                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
550                         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
551                         emit_bytes (acfg, buf, code - buf);
552                         /* FIXME: Get rid of this */
553                         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
554                         /* Used by mono_aot_get_plt_info_offset */
555                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
556                 } else {
557                         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
558                         ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
559                         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
560                         emit_bytes (acfg, buf, code - buf);
561                         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
562                         /* Used by mono_aot_get_plt_info_offset */
563                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
564                 }
565 #else
566                 g_assert_not_reached ();
567 #endif
568 }
569
570 /*
571  * arch_emit_specific_trampoline:
572  *
573  *   Emit code for a specific trampoline. OFFSET is the offset of the first of
574  * two GOT slots which contain the generic trampoline address and the trampoline
575  * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
576  */
577 static void
578 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
579 {
580         /*
581          * The trampolines created here are variations of the specific 
582          * trampolines created in mono_arch_create_specific_trampoline (). The 
583          * differences are:
584          * - the generic trampoline address is taken from a got slot.
585          * - the offset of the got slot where the trampoline argument is stored
586          *   is embedded in the instruction stream, and the generic trampoline
587          *   can load the argument by loading the offset, adding it to the
588          *   address of the trampoline to get the address of the got slot, and
589          *   loading the argument from there.
590          * - all the trampolines should be of the same length.
591          */
592 #if defined(TARGET_AMD64)
593         /* This should be exactly 16 bytes long */
594         *tramp_size = 16;
595         /* call *<offset>(%rip) */
596         emit_byte (acfg, '\x41');
597         emit_byte (acfg, '\xff');
598         emit_byte (acfg, '\x15');
599         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
600         /* This should be relative to the start of the trampoline */
601         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
602         emit_zero_bytes (acfg, 5);
603 #elif defined(TARGET_ARM)
604         guint8 buf [128];
605         guint8 *code;
606
607         /* This should be exactly 28 bytes long */
608         *tramp_size = 28;
609         code = buf;
610         ARM_PUSH (code, 0x5fff);
611         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
612         /* Load the value from the GOT */
613         ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
614         /* Branch to it */
615         ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
616         ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
617
618         g_assert (code - buf == 20);
619
620         /* Emit it */
621         emit_bytes (acfg, buf, code - buf);
622         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
623         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
624 #else
625         g_assert_not_reached ();
626 #endif
627 }
628
629 /*
630  * arch_emit_unbox_trampoline:
631  *
632  *   Emit code for the unbox trampoline for METHOD used in the full-aot case.
633  * CALL_TARGET is the symbol pointing to the native code of METHOD.
634  */
635 static void
636 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
637 {
638 #if defined(TARGET_AMD64)
639         guint8 buf [32];
640         guint8 *code;
641         int this_reg;
642
643         this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
644         code = buf;
645         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
646
647         emit_bytes (acfg, buf, code - buf);
648         /* jump <method> */
649         emit_byte (acfg, '\xe9');
650         emit_symbol_diff (acfg, call_target, ".", -4);
651 #elif defined(TARGET_ARM)
652         guint8 buf [128];
653         guint8 *code;
654         int this_pos = 0;
655
656         code = buf;
657
658         if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
659                 this_pos = 1;
660
661         ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
662
663         emit_bytes (acfg, buf, code - buf);
664         /* jump to method */
665         if (acfg->use_bin_writer) {
666                 guint8 buf [4];
667                 guint8 *code;
668
669                 code = buf;
670                 ARM_B (code, 0);
671
672                 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
673                 emit_bytes (acfg, buf, 4);
674         } else {
675                 fprintf (acfg->fp, "\n\tb %s\n", call_target);
676         }
677 #else
678         g_assert_not_reached ();
679 #endif
680 }
681
682 /*
683  * arch_emit_static_rgctx_trampoline:
684  *
685  *   Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
686  * two GOT slots which contain the rgctx argument, and the method to jump to.
687  * TRAMP_SIZE is set to the size of the emitted trampoline.
688  * These kinds of trampolines cannot be enumerated statically, since there could
689  * be one trampoline per method instantiation, so we emit the same code for all
690  * trampolines, and parameterize them using two GOT slots.
691  */
692 static void
693 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
694 {
695 #if defined(TARGET_AMD64)
696         /* This should be exactly 13 bytes long */
697         *tramp_size = 13;
698
699         /* mov <OFFSET>(%rip), %r10 */
700         emit_byte (acfg, '\x4d');
701         emit_byte (acfg, '\x8b');
702         emit_byte (acfg, '\x15');
703         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
704
705         /* jmp *<offset>(%rip) */
706         emit_byte (acfg, '\xff');
707         emit_byte (acfg, '\x25');
708         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
709 #elif defined(TARGET_ARM)
710         guint8 buf [128];
711         guint8 *code;
712
713         /* This should be exactly 24 bytes long */
714         *tramp_size = 24;
715         code = buf;
716         /* Load rgctx value */
717         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
718         ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_R1);
719         /* Load branch addr + branch */
720         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
721         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_R1);
722
723         g_assert (code - buf == 16);
724
725         /* Emit it */
726         emit_bytes (acfg, buf, code - buf);
727         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
728         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
729 #else
730         g_assert_not_reached ();
731 #endif
732 }       
733
734 /*
735  * arch_emit_imt_thunk:
736  *
737  *   Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
738  * points to an array of pointer pairs. The pairs of the form [key, ptr], where
739  * key is the IMT key, and ptr holds the address of a memory location holding
740  * the address to branch to if the IMT arg matches the key. The array is 
741  * terminated by a pair whose key is NULL, and whose ptr is the address of the 
742  * fail_tramp.
743  * TRAMP_SIZE is set to the size of the emitted trampoline.
744  */
745 static void
746 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
747 {
748 #if defined(TARGET_AMD64)
749         guint8 *buf, *code;
750         guint8 *labels [3];
751
752         code = buf = g_malloc (256);
753
754         /* FIXME: Optimize this, i.e. use binary search etc. */
755         /* Maybe move the body into a separate function (slower, but much smaller) */
756
757         /* R10 is a free register */
758
759         labels [0] = code;
760         amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
761         labels [1] = code;
762         amd64_branch8 (code, X86_CC_Z, FALSE, 0);
763
764         /* Check key */
765         amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
766         labels [2] = code;
767         amd64_branch8 (code, X86_CC_Z, FALSE, 0);
768
769         /* Loop footer */
770         amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
771         amd64_jump_code (code, labels [0]);
772
773         /* Match */
774         mono_amd64_patch (labels [2], code);
775         amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
776         amd64_jump_membase (code, AMD64_R10, 0);
777
778         /* No match */
779         /* FIXME: */
780         mono_amd64_patch (labels [1], code);
781         x86_breakpoint (code);
782
783         /* mov <OFFSET>(%rip), %r10 */
784         emit_byte (acfg, '\x4d');
785         emit_byte (acfg, '\x8b');
786         emit_byte (acfg, '\x15');
787         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
788
789         emit_bytes (acfg, buf, code - buf);
790         
791         *tramp_size = code - buf + 7;
792 #elif defined(TARGET_ARM)
793         guint8 buf [128];
794         guint8 *code, *code2, *labels [16];
795
796         code = buf;
797
798         /* The IMT method is in v5 */
799
800         /* Only IP is available, but we need at least two free registers */
801         ARM_PUSH1 (code, ARMREG_R1);
802         labels [0] = code;
803         /* Load the parameter from the GOT */
804         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
805         ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
806
807         labels [1] = code;
808         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_IP, 0);
809         ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
810         labels [2] = code;
811         ARM_B_COND (code, ARMCOND_EQ, 0);
812
813         /* End-of-loop check */
814         ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
815         labels [3] = code;
816         ARM_B_COND (code, ARMCOND_EQ, 0);
817
818         /* Loop footer */
819         ARM_ADD_REG_IMM8 (code, ARMREG_IP, ARMREG_IP, sizeof (gpointer) * 2);
820         labels [4] = code;
821         ARM_B (code, 0);
822         arm_patch (labels [4], labels [1]);
823
824         /* Match */
825         arm_patch (labels [2], code);
826         ARM_POP1 (code, ARMREG_R1);
827         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_IP, 4);
828         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
829
830         /* No match */
831         arm_patch (labels [3], code);
832         ARM_DBRK (code);
833
834         /* Fixup offset */
835         code2 = labels [0];
836         ARM_LDR_IMM (code2, ARMREG_IP, ARMREG_PC, (code - (labels [0] + 8)));
837
838         emit_bytes (acfg, buf, code - buf);
839         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
840
841         *tramp_size = code - buf + 4;
842 #else
843         g_assert_not_reached ();
844 #endif
845 }
846
847 /*
848  * arch_get_cie_program:
849  *
850  *   Get the unwind bytecode for the DWARF CIE.
851  */
852 static GSList*
853 arch_get_cie_program (void)
854 {
855 #ifdef TARGET_AMD64
856         GSList *l = NULL;
857
858         mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
859         mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
860
861         return l;
862 #else
863         return NULL;
864 #endif
865 }
866
867 /* END OF ARCH SPECIFIC CODE */
868
869 static guint32
870 mono_get_field_token (MonoClassField *field) 
871 {
872         MonoClass *klass = field->parent;
873         int i;
874
875         for (i = 0; i < klass->field.count; ++i) {
876                 if (field == &klass->fields [i])
877                         return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
878         }
879
880         g_assert_not_reached ();
881         return 0;
882 }
883
884 static inline void
885 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
886 {
887         guint8 *p = buf;
888
889         //printf ("ENCODE: %d 0x%x.\n", value, value);
890
891         /* 
892          * Same encoding as the one used in the metadata, extended to handle values
893          * greater than 0x1fffffff.
894          */
895         if ((value >= 0) && (value <= 127))
896                 *p++ = value;
897         else if ((value >= 0) && (value <= 16383)) {
898                 p [0] = 0x80 | (value >> 8);
899                 p [1] = value & 0xff;
900                 p += 2;
901         } else if ((value >= 0) && (value <= 0x1fffffff)) {
902                 p [0] = (value >> 24) | 0xc0;
903                 p [1] = (value >> 16) & 0xff;
904                 p [2] = (value >> 8) & 0xff;
905                 p [3] = value & 0xff;
906                 p += 4;
907         }
908         else {
909                 p [0] = 0xff;
910                 p [1] = (value >> 24) & 0xff;
911                 p [2] = (value >> 16) & 0xff;
912                 p [3] = (value >> 8) & 0xff;
913                 p [4] = value & 0xff;
914                 p += 5;
915         }
916         if (endbuf)
917                 *endbuf = p;
918 }
919
920 static guint32
921 get_image_index (MonoAotCompile *cfg, MonoImage *image)
922 {
923         guint32 index;
924
925         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
926         if (index)
927                 return index - 1;
928         else {
929                 index = g_hash_table_size (cfg->image_hash);
930                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
931                 g_ptr_array_add (cfg->image_table, image);
932                 return index;
933         }
934 }
935
936 static guint32
937 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
938 {
939         int i;
940         MonoClass *k = NULL;
941
942         /* FIXME: Search referenced images as well */
943         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
944                 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
945                 if (k == klass)
946                         break;
947         }
948
949         if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
950                 return MONO_TOKEN_TYPE_SPEC | (i + 1);
951         else
952                 return 0;
953 }
954
955 static void
956 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
957
958 /*
959  * encode_klass_ref:
960  *
961  *   Encode a reference to KLASS. We use our home-grown encoding instead of the
962  * standard metadata encoding.
963  */
964 static void
965 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
966 {
967         guint8 *p = buf;
968
969         if (klass->generic_class) {
970                 guint32 token;
971                 g_assert (klass->type_token);
972
973                 /* Find a typespec for a class if possible */
974                 token = find_typespec_for_class (acfg, klass);
975                 if (token) {
976                         encode_value (token, p, &p);
977                         encode_value (get_image_index (acfg, acfg->image), p, &p);
978                 } else {
979                         MonoClass *gclass = klass->generic_class->container_class;
980                         MonoGenericInst *inst = klass->generic_class->context.class_inst;
981                         int i;
982
983                         /* Encode it ourselves */
984                         /* Marker */
985                         encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
986                         encode_value (MONO_TYPE_GENERICINST, p, &p);
987                         encode_klass_ref (acfg, gclass, p, &p);
988                         encode_value (inst->type_argc, p, &p);
989                         for (i = 0; i < inst->type_argc; ++i)
990                                 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
991                 }
992         } else if (klass->type_token) {
993                 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
994                 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
995                 encode_value (get_image_index (acfg, klass->image), p, &p);
996         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
997                 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
998                 g_assert (container);
999
1000                 /* Marker */
1001                 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1002                 encode_value (klass->byval_arg.type, p, &p);
1003
1004                 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1005                 
1006                 encode_value (container->is_method, p, &p);
1007                 if (container->is_method)
1008                         encode_method_ref (acfg, container->owner.method, p, &p);
1009                 else
1010                         encode_klass_ref (acfg, container->owner.klass, p, &p);
1011         } else {
1012                 /* Array class */
1013                 g_assert (klass->rank > 0);
1014                 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1015                 encode_value (get_image_index (acfg, klass->image), p, &p);
1016                 encode_value (klass->rank, p, &p);
1017                 encode_klass_ref (acfg, klass->element_class, p, &p);
1018         }
1019         *endbuf = p;
1020 }
1021
1022 static void
1023 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1024 {
1025         guint32 token = mono_get_field_token (field);
1026         guint8 *p = buf;
1027
1028         encode_klass_ref (cfg, field->parent, p, &p);
1029         g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1030         encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1031         *endbuf = p;
1032 }
1033
1034 static void
1035 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1036 {
1037         guint8 *p = buf;
1038         int i;
1039         MonoGenericInst *inst;
1040
1041         /* Encode the context */
1042         inst = context->class_inst;
1043         encode_value (inst ? 1 : 0, p, &p);
1044         if (inst) {
1045                 encode_value (inst->type_argc, p, &p);
1046                 for (i = 0; i < inst->type_argc; ++i)
1047                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1048         }
1049         inst = context->method_inst;
1050         encode_value (inst ? 1 : 0, p, &p);
1051         if (inst) {
1052                 encode_value (inst->type_argc, p, &p);
1053                 for (i = 0; i < inst->type_argc; ++i)
1054                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1055         }
1056
1057         *endbuf = p;
1058 }
1059
1060 #define MAX_IMAGE_INDEX 250
1061
1062 static void
1063 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1064 {
1065         guint32 image_index = get_image_index (acfg, method->klass->image);
1066         guint32 token = method->token;
1067         MonoJumpInfoToken *ji;
1068         guint8 *p = buf;
1069         char *name;
1070
1071         /*
1072          * The encoding for most methods is as follows:
1073          * - image index encoded as a leb128
1074          * - token index encoded as a leb128
1075          * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1076          * types of method encodings.
1077          */
1078
1079         g_assert (image_index < MONO_AOT_METHODREF_MIN);
1080
1081         /* Mark methods which can't use aot trampolines because they need the further 
1082          * processing in mono_magic_trampoline () which requires a MonoMethod*.
1083          */
1084         if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1085                 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1086                 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1087
1088         /* 
1089          * Some wrapper methods are shared using their signature, encode their 
1090          * stringified signature instead.
1091          * FIXME: Optimize disk usage
1092          */
1093         name = NULL;
1094         if (method->wrapper_type) {
1095                 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1096                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1097                         if (mono_marshal_method_from_wrapper (method) != method) {
1098                                 /* Direct wrapper, encode it normally */
1099                         } else {
1100                                 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1101                         }
1102                         g_free (tmpsig);
1103                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1104                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1105                         name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1106                         g_free (tmpsig);
1107                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1108                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1109                         name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1110                         g_free (tmpsig);
1111                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1112                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1113                         name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1114                         g_free (tmpsig);
1115                 }
1116         }
1117
1118         if (name) {
1119                 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1120                 strcpy ((char*)p, name);
1121                 p += strlen (name) + 1;
1122                 g_free (name);
1123         } else if (method->wrapper_type) {
1124                 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1125
1126                 encode_value (method->wrapper_type, p, &p);
1127
1128                 switch (method->wrapper_type) {
1129                 case MONO_WRAPPER_REMOTING_INVOKE:
1130                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1131                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1132                         MonoMethod *m;
1133
1134                         m = mono_marshal_method_from_wrapper (method);
1135                         g_assert (m);
1136                         encode_method_ref (acfg, m, p, &p);
1137                         break;
1138                 }
1139                 case MONO_WRAPPER_PROXY_ISINST:
1140                 case MONO_WRAPPER_LDFLD:
1141                 case MONO_WRAPPER_LDFLDA:
1142                 case MONO_WRAPPER_STFLD:
1143                 case MONO_WRAPPER_ISINST: {
1144                         MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1145                         encode_klass_ref (acfg, proxy_class, p, &p);
1146                         break;
1147                 }
1148                 case MONO_WRAPPER_LDFLD_REMOTE:
1149                 case MONO_WRAPPER_STFLD_REMOTE:
1150                         break;
1151                 case MONO_WRAPPER_ALLOC: {
1152                         int alloc_type = mono_gc_get_managed_allocator_type (method);
1153                         g_assert (alloc_type != -1);
1154                         encode_value (alloc_type, p, &p);
1155                         break;
1156                 }
1157                 case MONO_WRAPPER_STELEMREF:
1158                         break;
1159                 case MONO_WRAPPER_UNKNOWN:
1160                         if (strcmp (method->name, "FastMonitorEnter") == 0)
1161                                 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1162                         else if (strcmp (method->name, "FastMonitorExit") == 0)
1163                                 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1164                         else
1165                                 g_assert_not_reached ();
1166                         break;
1167                 case MONO_WRAPPER_SYNCHRONIZED:
1168                 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1169                 case MONO_WRAPPER_RUNTIME_INVOKE: {
1170                         MonoMethod *m;
1171
1172                         m = mono_marshal_method_from_wrapper (method);
1173                         g_assert (m);
1174                         g_assert (m != method);
1175                         encode_method_ref (acfg, m, p, &p);
1176                         break;
1177                 }
1178                 default:
1179                         g_assert_not_reached ();
1180                 }
1181         } else if (mono_method_signature (method)->is_inflated) {
1182                 /* 
1183                  * This is a generic method, find the original token which referenced it and
1184                  * encode that.
1185                  * Obtain the token from information recorded by the JIT.
1186                  */
1187                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1188                 if (ji) {
1189                         image_index = get_image_index (acfg, ji->image);
1190                         g_assert (image_index < MAX_IMAGE_INDEX);
1191                         token = ji->token;
1192
1193                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1194                         encode_value (image_index, p, &p);
1195                         encode_value (token, p, &p);
1196                 } else {
1197                         MonoMethod *declaring;
1198                         MonoGenericContext *context = mono_method_get_context (method);
1199
1200                         g_assert (method->is_inflated);
1201                         declaring = ((MonoMethodInflated*)method)->declaring;
1202
1203                         /*
1204                          * This might be a non-generic method of a generic instance, which 
1205                          * doesn't have a token since the reference is generated by the JIT 
1206                          * like Nullable:Box/Unbox, or by generic sharing.
1207                          */
1208
1209                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1210                         /* Encode the klass */
1211                         encode_klass_ref (acfg, method->klass, p, &p);
1212                         /* Encode the method */
1213                         image_index = get_image_index (acfg, method->klass->image);
1214                         g_assert (image_index < MAX_IMAGE_INDEX);
1215                         g_assert (declaring->token);
1216                         token = declaring->token;
1217                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1218                         encode_value (image_index, p, &p);
1219                         encode_value (token, p, &p);
1220                         encode_generic_context (acfg, context, p, &p);
1221                 }
1222         } else if (token == 0) {
1223                 /* This might be a method of a constructed type like int[,].Set */
1224                 /* Obtain the token from information recorded by the JIT */
1225                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1226                 if (ji) {
1227                         image_index = get_image_index (acfg, ji->image);
1228                         g_assert (image_index < MAX_IMAGE_INDEX);
1229                         token = ji->token;
1230
1231                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1232                         encode_value (image_index, p, &p);
1233                         encode_value (token, p, &p);
1234                 } else {
1235                         /* Array methods */
1236                         g_assert (method->klass->rank);
1237
1238                         /* Encode directly */
1239                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1240                         encode_klass_ref (acfg, method->klass, p, &p);
1241                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1242                                 encode_value (0, p, &p);
1243                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1244                                 encode_value (1, p, &p);
1245                         else if (!strcmp (method->name, "Get"))
1246                                 encode_value (2, p, &p);
1247                         else if (!strcmp (method->name, "Address"))
1248                                 encode_value (3, p, &p);
1249                         else if (!strcmp (method->name, "Set"))
1250                                 encode_value (4, p, &p);
1251                         else
1252                                 g_assert_not_reached ();
1253                 }
1254         } else {
1255                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1256                 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1257         }
1258         *endbuf = p;
1259 }
1260
1261 static gint
1262 compare_patches (gconstpointer a, gconstpointer b)
1263 {
1264         int i, j;
1265
1266         i = (*(MonoJumpInfo**)a)->ip.i;
1267         j = (*(MonoJumpInfo**)b)->ip.i;
1268
1269         if (i < j)
1270                 return -1;
1271         else
1272                 if (i > j)
1273                         return 1;
1274         else
1275                 return 0;
1276 }
1277
1278 /*
1279  * is_plt_patch:
1280  *
1281  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
1282  * PLT entry.
1283  */
1284 static inline gboolean
1285 is_plt_patch (MonoJumpInfo *patch_info)
1286 {
1287         switch (patch_info->type) {
1288         case MONO_PATCH_INFO_METHOD:
1289         case MONO_PATCH_INFO_INTERNAL_METHOD:
1290         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1291         case MONO_PATCH_INFO_ICALL_ADDR:
1292         case MONO_PATCH_INFO_CLASS_INIT:
1293         case MONO_PATCH_INFO_RGCTX_FETCH:
1294         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1295         case MONO_PATCH_INFO_MONITOR_ENTER:
1296         case MONO_PATCH_INFO_MONITOR_EXIT:
1297                 return TRUE;
1298         default:
1299                 return FALSE;
1300         }
1301 }
1302
1303 static int
1304 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1305 {
1306         int res = -1;
1307
1308         if (is_plt_patch (patch_info)) {
1309                 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1310
1311                 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1312                         /* 
1313                          * Allocate a separate PLT slot for each such patch, since some plt
1314                          * entries will refer to the method itself, and some will refer to
1315                          * wrapper.
1316                          */
1317                         idx = 0;
1318                 }
1319
1320                 if (idx) {
1321                         res = idx;
1322                 } else {
1323                         MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1324
1325                         res = acfg->plt_offset;
1326                         g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1327                         g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1328                         acfg->plt_offset ++;
1329                 }
1330         }
1331
1332         return res;
1333 }
1334
1335 /**
1336  * get_got_offset:
1337  *
1338  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
1339  * JI could be found if it exists, otherwise allocates a new one.
1340  */
1341 static guint32
1342 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1343 {
1344         guint32 got_offset;
1345
1346         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset, ji));
1347         if (got_offset)
1348                 return got_offset - 1;
1349
1350         got_offset = acfg->got_offset;
1351         acfg->got_offset ++;
1352
1353         acfg->stats.got_slots ++;
1354         acfg->stats.got_slot_types [ji->type] ++;
1355
1356         g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
1357         g_ptr_array_add (acfg->got_patches, ji);
1358
1359         return got_offset;
1360 }
1361
1362 /* Add a method to the list of methods which need to be emitted */
1363 static void
1364 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1365 {
1366         g_assert (method);
1367         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1368                 g_ptr_array_add (acfg->methods, method);
1369                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1370                 acfg->nmethods = acfg->methods->len + 1;
1371         }
1372
1373         if (method->wrapper_type || extra)
1374                 g_ptr_array_add (acfg->extra_methods, method);
1375 }
1376
1377 static guint32
1378 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1379 {
1380         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1381         
1382         g_assert (index);
1383
1384         return index - 1;
1385 }
1386
1387 static int
1388 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra)
1389 {
1390         int index;
1391
1392         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1393         if (index)
1394                 return index - 1;
1395
1396         index = acfg->method_index;
1397         add_method_with_index (acfg, method, index, extra);
1398
1399         /* FIXME: Fix quadratic behavior */
1400         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1401
1402         acfg->method_index ++;
1403
1404         return index;
1405 }
1406
1407 static int
1408 add_method (MonoAotCompile *acfg, MonoMethod *method)
1409 {
1410         return add_method_full (acfg, method, FALSE);
1411 }
1412
1413 static void
1414 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1415 {
1416         add_method_full (acfg, method, TRUE);
1417 }
1418
1419 static void
1420 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1421 {
1422         MonoAotCompile *acfg = user_data;
1423         MonoJitICallInfo *callinfo = value;
1424         MonoMethod *wrapper;
1425         char *name;
1426
1427         if (!callinfo->sig)
1428                 return;
1429
1430         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1431         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1432         g_free (name);
1433
1434         add_method (acfg, wrapper);
1435 }
1436
1437 static MonoMethod*
1438 get_runtime_invoke_sig (MonoMethodSignature *sig)
1439 {
1440         MonoMethodBuilder *mb;
1441         MonoMethod *m;
1442
1443         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1444         m = mono_mb_create_method (mb, sig, 16);
1445         return mono_marshal_get_runtime_invoke (m, FALSE);
1446 }
1447
1448 static void
1449 add_wrappers (MonoAotCompile *acfg)
1450 {
1451         MonoMethod *method, *m;
1452         int i, j, nallocators;
1453         MonoMethodSignature *sig, *csig;
1454         guint32 token;
1455
1456         /* 
1457          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1458          * so there is only one wrapper of a given type, or inlining their contents into their
1459          * callers.
1460          */
1461
1462         /* 
1463          * FIXME: This depends on the fact that different wrappers have different 
1464          * names.
1465          */
1466
1467         /* FIXME: Collect these automatically */
1468
1469         /* Runtime invoke wrappers */
1470
1471         /* void runtime-invoke () [.cctor] */
1472         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1473         csig->ret = &mono_defaults.void_class->byval_arg;
1474         add_method (acfg, get_runtime_invoke_sig (csig));
1475
1476         /* void runtime-invoke () [Finalize] */
1477         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1478         csig->hasthis = 1;
1479         csig->ret = &mono_defaults.void_class->byval_arg;
1480         add_method (acfg, get_runtime_invoke_sig (csig));
1481
1482         /* void runtime-invoke (string) [exception ctor] */
1483         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1484         csig->hasthis = 1;
1485         csig->ret = &mono_defaults.void_class->byval_arg;
1486         csig->params [0] = &mono_defaults.string_class->byval_arg;
1487         add_method (acfg, get_runtime_invoke_sig (csig));
1488
1489         /* void runtime-invoke (string, string) [exception ctor] */
1490         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1491         csig->hasthis = 1;
1492         csig->ret = &mono_defaults.void_class->byval_arg;
1493         csig->params [0] = &mono_defaults.string_class->byval_arg;
1494         csig->params [1] = &mono_defaults.string_class->byval_arg;
1495         add_method (acfg, get_runtime_invoke_sig (csig));
1496
1497         /* string runtime-invoke () [Exception.ToString ()] */
1498         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1499         csig->hasthis = 1;
1500         csig->ret = &mono_defaults.string_class->byval_arg;
1501         add_method (acfg, get_runtime_invoke_sig (csig));
1502
1503         /* void runtime-invoke (string, Exception) [exception ctor] */
1504         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1505         csig->hasthis = 1;
1506         csig->ret = &mono_defaults.void_class->byval_arg;
1507         csig->params [0] = &mono_defaults.string_class->byval_arg;
1508         csig->params [1] = &mono_defaults.exception_class->byval_arg;
1509         add_method (acfg, get_runtime_invoke_sig (csig));
1510
1511         /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1512         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1513         csig->hasthis = 1;
1514         csig->ret = &(mono_class_from_name (
1515                                                                                 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1516         csig->params [0] = &mono_defaults.string_class->byval_arg;
1517         csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1518         add_method (acfg, get_runtime_invoke_sig (csig));
1519
1520         /* runtime-invoke used by finalizers */
1521         add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
1522
1523         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1524                 MonoMethod *method;
1525                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1526                 gboolean skip = FALSE;
1527
1528                 method = mono_get_method (acfg->image, token, NULL);
1529
1530                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1531                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1532                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1533                         skip = TRUE;
1534
1535                 if (method->is_generic || method->klass->generic_container)
1536                         skip = TRUE;
1537
1538                 /* Skip methods which can not be handled by get_runtime_invoke () */
1539                 sig = mono_method_signature (method);
1540                 if ((sig->ret->type == MONO_TYPE_PTR) ||
1541                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1542                         skip = TRUE;
1543
1544                 for (j = 0; j < sig->param_count; j++) {
1545                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1546                                 skip = TRUE;
1547                 }
1548
1549                 if (!skip)
1550                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1551         }
1552
1553         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1554                 MonoMethodDesc *desc;
1555                 MonoMethod *orig_method;
1556
1557                 /* JIT icall wrappers */
1558                 /* FIXME: locking */
1559                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1560
1561                 /* Managed Allocators */
1562                 nallocators = mono_gc_get_managed_allocator_types ();
1563                 for (i = 0; i < nallocators; ++i) {
1564                         m = mono_gc_get_managed_allocator_by_type (i);
1565                         if (m)
1566                                 add_method (acfg, m);
1567                 }
1568
1569                 /* stelemref */
1570                 add_method (acfg, mono_marshal_get_stelemref ());
1571
1572                 /* Monitor Enter/Exit */
1573                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1574                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1575                 g_assert (orig_method);
1576                 mono_method_desc_free (desc);
1577                 method = mono_monitor_get_fast_path (orig_method);
1578                 if (method)
1579                         add_method (acfg, method);
1580
1581                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1582                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1583                 g_assert (orig_method);
1584                 mono_method_desc_free (desc);
1585                 method = mono_monitor_get_fast_path (orig_method);
1586                 if (method)
1587                         add_method (acfg, method);
1588         }
1589
1590         /* remoting-invoke wrappers */
1591         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1592                 MonoMethodSignature *sig;
1593                 
1594                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1595                 method = mono_get_method (acfg->image, token, NULL);
1596
1597                 sig = mono_method_signature (method);
1598
1599                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
1600                         m = mono_marshal_get_remoting_invoke_with_check (method);
1601
1602                         add_method (acfg, m);
1603                 }
1604         }
1605
1606         /* delegate-invoke wrappers */
1607         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1608                 MonoClass *klass;
1609                 
1610                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1611                 klass = mono_class_get (acfg->image, token);
1612
1613                 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1614                         method = mono_get_delegate_invoke (klass);
1615
1616                         m = mono_marshal_get_delegate_invoke (method, NULL);
1617
1618                         add_method (acfg, m);
1619
1620                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1621                         add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1622
1623                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1624                         add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1625                 }
1626         }
1627
1628         /* Synchronized wrappers */
1629         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1630                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1631                 method = mono_get_method (acfg->image, token, NULL);
1632
1633                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1634                         add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1635         }
1636
1637         /* pinvoke wrappers */
1638         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1639                 MonoMethod *method;
1640                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1641
1642                 method = mono_get_method (acfg->image, token, NULL);
1643
1644                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1645                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1646                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1647                 }
1648         }
1649
1650         /* StructureToPtr/PtrToStructure wrappers */
1651         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1652                 MonoClass *klass;
1653                 
1654                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1655                 klass = mono_class_get (acfg->image, token);
1656
1657                 if (klass->valuetype && !klass->generic_container && ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)) {
1658                         MonoMarshalType *info;
1659                         gboolean can_marshal = TRUE;
1660                         int j;
1661
1662                         info = mono_marshal_load_type_info (klass);
1663
1664                         /* Only allow a few field types to avoid asserts in the marshalling code */
1665                         for (j = 0; j < info->num_fields; j++) {
1666                                 switch (info->fields [j].field->type->type) {
1667                                 case MONO_TYPE_I4:
1668                                 case MONO_TYPE_U4:
1669                                 case MONO_TYPE_I1:
1670                                 case MONO_TYPE_U1:
1671                                 case MONO_TYPE_BOOLEAN:
1672                                 case MONO_TYPE_I2:
1673                                 case MONO_TYPE_U2:
1674                                 case MONO_TYPE_CHAR:
1675                                 case MONO_TYPE_I8:
1676                                 case MONO_TYPE_U8:
1677                                 case MONO_TYPE_PTR:
1678                                 case MONO_TYPE_R4:
1679                                 case MONO_TYPE_R8:
1680                                         break;
1681                                 default:
1682                                         can_marshal = FALSE;
1683                                         break;
1684                                 }
1685                         }
1686
1687                         if (can_marshal) {
1688                                 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
1689                                 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
1690                         }
1691                 }
1692         }
1693 }
1694
1695 static gboolean
1696 has_type_vars (MonoClass *klass)
1697 {
1698         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
1699                 return TRUE;
1700         if (klass->rank)
1701                 return has_type_vars (klass->element_class);
1702         if (klass->generic_class) {
1703                 MonoGenericContext *context = &klass->generic_class->context;
1704                 if (context->class_inst) {
1705                         int i;
1706
1707                         for (i = 0; i < context->class_inst->type_argc; ++i)
1708                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
1709                                         return TRUE;
1710                 }
1711         }
1712         return FALSE;
1713 }
1714
1715 static gboolean
1716 method_has_type_vars (MonoMethod *method)
1717 {
1718         if (has_type_vars (method->klass))
1719                 return TRUE;
1720
1721         if (method->is_inflated) {
1722                 MonoGenericContext *context = mono_method_get_context (method);
1723                 if (context->method_inst) {
1724                         int i;
1725
1726                         for (i = 0; i < context->method_inst->type_argc; ++i)
1727                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
1728                                         return TRUE;
1729                 }
1730         }
1731         return FALSE;
1732 }
1733
1734 /*
1735  * add_generic_class:
1736  *
1737  *   Add all methods of a generic class.
1738  */
1739 static void
1740 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
1741 {
1742         MonoMethod *method;
1743         gpointer iter;
1744
1745         mono_class_init (klass);
1746
1747         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
1748                 return;
1749
1750         if (has_type_vars (klass))
1751                 return;
1752
1753         if (!klass->generic_class && !klass->rank)
1754                 return;
1755
1756         iter = NULL;
1757         while ((method = mono_class_get_methods (klass, &iter))) {
1758                 if (mono_method_is_generic_sharable_impl (method, FALSE))
1759                         /* Already added */
1760                         continue;
1761
1762                 if (method->is_generic)
1763                         /* FIXME: */
1764                         continue;
1765
1766                 /*
1767                  * FIXME: Instances which are referenced by these methods are not added,
1768                  * for example Array.Resize<int> for List<int>.Add ().
1769                  */
1770                 add_extra_method (acfg, method);
1771         }
1772
1773         /* 
1774          * For ICollection<T>, where T is a vtype, add instances of the helper methods
1775          * in Array, since a T[] could be cast to ICollection<T>.
1776          */
1777         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
1778                 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1")) &&
1779                 MONO_TYPE_ISSTRUCT (klass->generic_class->context.class_inst->type_argv [0])) {
1780                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
1781                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
1782                 gpointer iter;
1783                 char *name_prefix;
1784
1785                 if (!strcmp (klass->name, "IEnumerator`1"))
1786                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
1787                 else
1788                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
1789
1790                 /* Add the T[]/InternalEnumerator class */
1791                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
1792                         MonoClass *nclass;
1793
1794                         iter = NULL;
1795                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
1796                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
1797                                         break;
1798                         }
1799                         g_assert (nclass);
1800                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
1801                         add_generic_class (acfg, nclass);
1802                 }
1803
1804                 iter = NULL;
1805                 while ((method = mono_class_get_methods (array_class, &iter))) {
1806                         if (strstr (method->name, name_prefix))
1807                                 add_extra_method (acfg, method);
1808                 }
1809
1810                 g_free (name_prefix);
1811         }
1812 }
1813
1814 /*
1815  * add_generic_instances:
1816  *
1817  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
1818  */
1819 static void
1820 add_generic_instances (MonoAotCompile *acfg)
1821 {
1822         int i;
1823         guint32 token;
1824         MonoMethod *method;
1825         MonoMethodHeader *header;
1826         MonoMethodSignature *sig;
1827         MonoGenericContext *context;
1828
1829         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
1830                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
1831                 method = mono_get_method (acfg->image, token, NULL);
1832
1833                 context = mono_method_get_context (method);
1834                 if (context && ((context->class_inst && context->class_inst->is_open) ||
1835                                                 (context->method_inst && context->method_inst->is_open)))
1836                         continue;
1837
1838                 if (method->klass->image != acfg->image)
1839                         continue;
1840
1841                 if (mono_method_is_generic_sharable_impl (method, FALSE))
1842                         /* Already added */
1843                         continue;
1844
1845                 add_extra_method (acfg, method);
1846         }
1847
1848         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1849                 MonoClass *klass;
1850
1851                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
1852
1853                 klass = mono_class_get (acfg->image, token);
1854                 if (!klass || klass->rank)
1855                         continue;
1856
1857                 add_generic_class (acfg, klass);
1858         }
1859
1860         /* Add types of args/locals */
1861         for (i = 0; i < acfg->methods->len; ++i) {
1862                 int j;
1863
1864                 method = g_ptr_array_index (acfg->methods, i);
1865
1866                 sig = mono_method_signature (method);
1867
1868                 if (sig) {
1869                         for (j = 0; j < sig->param_count; ++j)
1870                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
1871                                         add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
1872                 }
1873
1874                 header = mono_method_get_header (method);
1875
1876                 if (header) {
1877                         for (j = 0; j < header->num_locals; ++j)
1878                                 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
1879                                         add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
1880                 }
1881         }
1882 }
1883
1884 /*
1885  * emit_and_reloc_code:
1886  *
1887  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
1888  * is true, calls are made through the GOT too. This is used for emitting trampolines
1889  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
1890  * since trampolines are needed to make PTL work.
1891  */
1892 static void
1893 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
1894 {
1895         int i, pindex, start_index, method_index;
1896         GPtrArray *patches;
1897         MonoJumpInfo *patch_info;
1898         MonoMethodHeader *header;
1899         gboolean skip, direct_call;
1900         guint32 got_slot;
1901         char direct_call_target [128];
1902
1903         if (method) {
1904                 header = mono_method_get_header (method);
1905
1906                 method_index = get_method_index (acfg, method);
1907         }
1908
1909         /* Collect and sort relocations */
1910         patches = g_ptr_array_new ();
1911         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
1912                 g_ptr_array_add (patches, patch_info);
1913         g_ptr_array_sort (patches, compare_patches);
1914
1915         start_index = 0;
1916         for (i = 0; i < code_len; i++) {
1917                 patch_info = NULL;
1918                 for (pindex = start_index; pindex < patches->len; ++pindex) {
1919                         patch_info = g_ptr_array_index (patches, pindex);
1920                         if (patch_info->ip.i >= i)
1921                                 break;
1922                 }
1923
1924 #ifdef MONO_ARCH_AOT_SUPPORTED
1925                 skip = FALSE;
1926                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
1927                         start_index = pindex;
1928
1929                         switch (patch_info->type) {
1930                         case MONO_PATCH_INFO_NONE:
1931                                 break;
1932                         case MONO_PATCH_INFO_GOT_OFFSET: {
1933                                 int code_size;
1934  
1935                                 arch_emit_got_offset (acfg, code + i, &code_size);
1936                                 i += code_size - 1;
1937                                 skip = TRUE;
1938                                 break;
1939                         }
1940                         default: {
1941                                 /*
1942                                  * If this patch is a call, try emitting a direct call instead of
1943                                  * through a PLT entry. This is possible if the called method is in
1944                                  * the same assembly and requires no initialization.
1945                                  */
1946                                 direct_call = FALSE;
1947                                 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
1948                                         MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
1949                                         if (callee_cfg) {
1950                                                 gboolean direct_callable = TRUE;
1951
1952                                                 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
1953                                                         direct_callable = FALSE;
1954                                                 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
1955                                                         // FIXME: Maybe call the wrapper directly ?
1956                                                         direct_callable = FALSE;
1957                                                 if (direct_callable) {
1958                                                         //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
1959                                                         direct_call = TRUE;
1960                                                         sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
1961                                                         patch_info->type = MONO_PATCH_INFO_NONE;
1962                                                         acfg->stats.direct_calls ++;
1963                                                 }
1964                                         }
1965
1966                                         acfg->stats.all_calls ++;
1967                                 }
1968
1969                                 if (!got_only && !direct_call) {
1970                                         int plt_offset = get_plt_offset (acfg, patch_info);
1971                                         if (plt_offset != -1) {
1972                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
1973                                                 direct_call = TRUE;
1974                                                 sprintf (direct_call_target, ".Lp_%d", plt_offset);
1975                 
1976                                                 /* Nullify the patch */
1977                                                 patch_info->type = MONO_PATCH_INFO_NONE;
1978                                         }
1979                                 }
1980
1981                                 if (direct_call) {
1982                                         int call_size;
1983
1984                                         arch_emit_direct_call (acfg, direct_call_target, &call_size);
1985                                         i += call_size - 1;
1986                                 } else {
1987                                         int code_size;
1988
1989                                         got_slot = get_got_offset (acfg, patch_info);
1990
1991                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
1992                                         i += code_size - 1;
1993                                 }
1994                                 skip = TRUE;
1995                         }
1996                         }
1997                 }
1998 #endif /* MONO_ARCH_AOT_SUPPORTED */
1999
2000                 if (!skip) {
2001                         /* Find next patch */
2002                         patch_info = NULL;
2003                         for (pindex = start_index; pindex < patches->len; ++pindex) {
2004                                 patch_info = g_ptr_array_index (patches, pindex);
2005                                 if (patch_info->ip.i >= i)
2006                                         break;
2007                         }
2008
2009                         /* Try to emit multiple bytes at once */
2010                         if (pindex < patches->len && patch_info->ip.i > i) {
2011                                 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2012                                 i = patch_info->ip.i - 1;
2013                         } else {
2014                                 emit_bytes (acfg, code + i, 1);
2015                         }
2016                 }
2017         }
2018 }
2019
2020 static void
2021 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2022 {
2023         MonoMethod *method;
2024         int method_index;
2025         guint8 *code;
2026         char symbol [128];
2027         int func_alignment = 16;
2028         MonoMethodHeader *header;
2029
2030         method = cfg->orig_method;
2031         code = cfg->native_code;
2032         header = mono_method_get_header (method);
2033
2034         method_index = get_method_index (acfg, method);
2035
2036         /* Make the labels local */
2037         sprintf (symbol, ".Lm_%x", method_index);
2038
2039         emit_alignment (acfg, func_alignment);
2040         emit_label (acfg, symbol);
2041
2042         if (acfg->aot_opts.write_symbols) {
2043                 char *name1, *name2, *cached;
2044                 int i, j, len, count;
2045
2046                 /* 
2047                  * Write a C style symbol for every method, this has two uses:
2048                  * - it works on platforms where the dwarf debugging info is not
2049                  *   yet supported.
2050                  * - it allows the setting of breakpoints of aot-ed methods.
2051                  */
2052                 name1 = mono_method_full_name (method, TRUE);
2053                 len = strlen (name1);
2054                 name2 = malloc (len + 1);
2055                 j = 0;
2056                 for (i = 0; i < len; ++i) {
2057                         if (isalnum (name1 [i])) {
2058                                 name2 [j ++] = name1 [i];
2059                         } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2060                                 i += 2;
2061                         } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2062                                 name2 [j ++] = '_';
2063                                 i++;
2064                         } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2065                         } else
2066                                 name2 [j ++] = '_';
2067                 }
2068                 name2 [j] = '\0';
2069
2070                 count = 0;
2071                 while (g_hash_table_lookup (acfg->method_label_hash, name2)) {
2072                         sprintf (name2 + j, "_%d", count);
2073                         count ++;
2074                 }
2075
2076                 cached = g_strdup (name2);
2077                 g_hash_table_insert (acfg->method_label_hash, cached, cached);
2078
2079                 sprintf (symbol, ".Lme_%x", method_index);
2080                 emit_local_symbol (acfg, name2, symbol, TRUE);
2081                 emit_label (acfg, name2);
2082                 g_free (name1);
2083                 g_free (name2);
2084         }
2085
2086         if (cfg->verbose_level > 0)
2087                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2088
2089         acfg->stats.code_size += cfg->code_len;
2090
2091         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2092
2093         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2094
2095         emit_line (acfg);
2096
2097         sprintf (symbol, ".Lme_%x", method_index);
2098         emit_label (acfg, symbol);
2099 }
2100
2101 /**
2102  * encode_patch:
2103  *
2104  *  Encode PATCH_INFO into its disk representation.
2105  */
2106 static void
2107 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2108 {
2109         guint8 *p = buf;
2110
2111         switch (patch_info->type) {
2112         case MONO_PATCH_INFO_NONE:
2113                 break;
2114         case MONO_PATCH_INFO_IMAGE:
2115                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2116                 break;
2117         case MONO_PATCH_INFO_METHOD_REL:
2118                 encode_value ((gint)patch_info->data.offset, p, &p);
2119                 break;
2120         case MONO_PATCH_INFO_SWITCH: {
2121                 gpointer *table = (gpointer *)patch_info->data.table->table;
2122                 int k;
2123
2124                 encode_value (patch_info->data.table->table_size, p, &p);
2125                 for (k = 0; k < patch_info->data.table->table_size; k++)
2126                         encode_value ((int)(gssize)table [k], p, &p);
2127                 break;
2128         }
2129         case MONO_PATCH_INFO_METHODCONST:
2130         case MONO_PATCH_INFO_METHOD:
2131         case MONO_PATCH_INFO_METHOD_JUMP:
2132         case MONO_PATCH_INFO_ICALL_ADDR:
2133         case MONO_PATCH_INFO_METHOD_RGCTX:
2134                 encode_method_ref (acfg, patch_info->data.method, p, &p);
2135                 break;
2136         case MONO_PATCH_INFO_INTERNAL_METHOD:
2137         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2138                 guint32 len = strlen (patch_info->data.name);
2139
2140                 encode_value (len, p, &p);
2141
2142                 memcpy (p, patch_info->data.name, len);
2143                 p += len;
2144                 *p++ = '\0';
2145                 break;
2146         }
2147         case MONO_PATCH_INFO_LDSTR: {
2148                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2149                 guint32 token = patch_info->data.token->token;
2150                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2151                 encode_value (image_index, p, &p);
2152                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2153                 break;
2154         }
2155         case MONO_PATCH_INFO_RVA:
2156         case MONO_PATCH_INFO_DECLSEC:
2157         case MONO_PATCH_INFO_LDTOKEN:
2158         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2159                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2160                 encode_value (patch_info->data.token->token, p, &p);
2161                 encode_value (patch_info->data.token->has_context, p, &p);
2162                 if (patch_info->data.token->has_context)
2163                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2164                 break;
2165         case MONO_PATCH_INFO_EXC_NAME: {
2166                 MonoClass *ex_class;
2167
2168                 ex_class =
2169                         mono_class_from_name (mono_defaults.exception_class->image,
2170                                                                   "System", patch_info->data.target);
2171                 g_assert (ex_class);
2172                 encode_klass_ref (acfg, ex_class, p, &p);
2173                 break;
2174         }
2175         case MONO_PATCH_INFO_R4:
2176                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2177                 break;
2178         case MONO_PATCH_INFO_R8:
2179                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2180                 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2181                 break;
2182         case MONO_PATCH_INFO_VTABLE:
2183         case MONO_PATCH_INFO_CLASS:
2184         case MONO_PATCH_INFO_IID:
2185         case MONO_PATCH_INFO_ADJUSTED_IID:
2186                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2187                 break;
2188         case MONO_PATCH_INFO_CLASS_INIT:
2189         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2190                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2191                 break;
2192         case MONO_PATCH_INFO_FIELD:
2193         case MONO_PATCH_INFO_SFLDA:
2194                 encode_field_info (acfg, patch_info->data.field, p, &p);
2195                 break;
2196         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2197                 break;
2198         case MONO_PATCH_INFO_RGCTX_FETCH: {
2199                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2200
2201                 encode_method_ref (acfg, entry->method, p, &p);
2202                 encode_value (entry->in_mrgctx, p, &p);
2203                 encode_value (entry->info_type, p, &p);
2204                 encode_value (entry->data->type, p, &p);
2205                 encode_patch (acfg, entry->data, p, &p);
2206                 break;
2207         }
2208         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2209         case MONO_PATCH_INFO_MONITOR_ENTER:
2210         case MONO_PATCH_INFO_MONITOR_EXIT:
2211                 break;
2212         default:
2213                 g_warning ("unable to handle jump info %d", patch_info->type);
2214                 g_assert_not_reached ();
2215         }
2216
2217         *endbuf = p;
2218 }
2219
2220 static void
2221 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2222 {
2223         guint8 *p = buf;
2224         guint32 pindex, offset;
2225         MonoJumpInfo *patch_info;
2226
2227         encode_value (n_patches, p, &p);
2228
2229         if (n_patches)
2230                 encode_value (first_got_offset, p, &p);
2231
2232         for (pindex = 0; pindex < patches->len; ++pindex) {
2233                 patch_info = g_ptr_array_index (patches, pindex);
2234
2235                 if (patch_info->type == MONO_PATCH_INFO_NONE)
2236                         /* Nothing to do */
2237                         continue;
2238
2239                 offset = get_got_offset (acfg, patch_info);
2240                 encode_value (offset, p, &p);
2241         }
2242
2243         *endbuf = p;
2244 }
2245
2246 static void
2247 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2248 {
2249         MonoMethod *method;
2250         GList *l;
2251         int pindex, buf_size, n_patches;
2252         guint8 *code;
2253         char symbol [128];
2254         GPtrArray *patches;
2255         MonoJumpInfo *patch_info;
2256         MonoMethodHeader *header;
2257         guint32 method_index;
2258         guint8 *p, *buf;
2259         guint32 first_got_offset;
2260
2261         method = cfg->orig_method;
2262         code = cfg->native_code;
2263         header = mono_method_get_header (method);
2264
2265         method_index = get_method_index (acfg, method);
2266
2267         /* Make the labels local */
2268         sprintf (symbol, ".Lm_%x_p", method_index);
2269
2270         /* Sort relocations */
2271         patches = g_ptr_array_new ();
2272         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2273                 g_ptr_array_add (patches, patch_info);
2274         g_ptr_array_sort (patches, compare_patches);
2275
2276         first_got_offset = acfg->cfgs [method_index]->got_offset;
2277
2278         /**********************/
2279         /* Encode method info */
2280         /**********************/
2281
2282         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2283         p = buf = g_malloc (buf_size);
2284
2285         if (mono_class_get_cctor (method->klass))
2286                 encode_klass_ref (acfg, method->klass, p, &p);
2287         else
2288                 /* Not needed when loading the method */
2289                 encode_value (0, p, &p);
2290
2291         /* String table */
2292         if (cfg->opt & MONO_OPT_SHARED) {
2293                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2294                 for (l = cfg->ldstr_list; l; l = l->next) {
2295                         encode_value ((long)l->data, p, &p);
2296                 }
2297         }
2298         else
2299                 /* Used only in shared mode */
2300                 g_assert (!cfg->ldstr_list);
2301
2302         n_patches = 0;
2303         for (pindex = 0; pindex < patches->len; ++pindex) {
2304                 patch_info = g_ptr_array_index (patches, pindex);
2305                 
2306                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2307                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
2308                         patch_info->type = MONO_PATCH_INFO_NONE;
2309                         /* Nothing to do */
2310                         continue;
2311                 }
2312
2313                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2314                         /* Stored in a GOT slot initialized at module load time */
2315                         patch_info->type = MONO_PATCH_INFO_NONE;
2316                         continue;
2317                 }
2318
2319                 if (is_plt_patch (patch_info)) {
2320                         /* Calls are made through the PLT */
2321                         patch_info->type = MONO_PATCH_INFO_NONE;
2322                         continue;
2323                 }
2324
2325                 n_patches ++;
2326         }
2327
2328         if (n_patches)
2329                 g_assert (cfg->has_got_slots);
2330
2331         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2332
2333         acfg->stats.info_size += p - buf;
2334
2335         /* Emit method info */
2336
2337         emit_label (acfg, symbol);
2338
2339         g_assert (p - buf < buf_size);
2340         emit_bytes (acfg, buf, p - buf);
2341         g_free (buf);
2342 }
2343
2344 static guint32
2345 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
2346 {
2347         guint32 cache_index;
2348         guint32 offset;
2349
2350         /* Reuse the unwind module to canonize and store unwind info entries */
2351         cache_index = mono_cache_unwind_info (encoded, encoded_len);
2352
2353         /* Use +/- 1 to distinguish 0s from missing entries */
2354         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
2355         if (offset)
2356                 return offset - 1;
2357         else {
2358                 guint8 buf [16];
2359                 guint8 *p;
2360
2361                 /* 
2362                  * It would be easier to use assembler symbols, but the caller needs an
2363                  * offset now.
2364                  */
2365                 offset = acfg->unwind_info_offset;
2366                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
2367                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
2368
2369                 p = buf;
2370                 encode_value (encoded_len, p, &p);
2371
2372                 acfg->unwind_info_offset += encoded_len + (p - buf);
2373                 return offset;
2374         }
2375 }
2376
2377 static void
2378 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2379 {
2380         MonoMethod *method;
2381         int k, buf_size, method_index;
2382         guint32 debug_info_size;
2383         guint8 *code;
2384         char symbol [128];
2385         MonoMethodHeader *header;
2386         guint8 *p, *buf, *debug_info;
2387         MonoJitInfo *jinfo = cfg->jit_info;
2388         guint32 flags;
2389         gboolean use_unwind_ops = FALSE;
2390
2391         method = cfg->orig_method;
2392         code = cfg->native_code;
2393         header = mono_method_get_header (method);
2394
2395         method_index = get_method_index (acfg, method);
2396
2397         /* Make the labels local */
2398         sprintf (symbol, ".Le_%x_p", method_index);
2399
2400         if (!acfg->aot_opts.nodebug) {
2401                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2402         } else {
2403                 debug_info = NULL;
2404                 debug_info_size = 0;
2405         }
2406
2407         buf_size = header->num_clauses * 256 + debug_info_size + 1024;
2408         p = buf = g_malloc (buf_size);
2409
2410 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2411         use_unwind_ops = cfg->unwind_ops != NULL;
2412 #endif
2413
2414         flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0);
2415
2416         encode_value (jinfo->code_size, p, &p);
2417         encode_value (flags, p, &p);
2418
2419         if (use_unwind_ops) {
2420                 guint32 encoded_len;
2421                 guint8 *encoded;
2422
2423                 /* 
2424                  * This is a duplicate of the data in the .debug_frame section, but that
2425                  * section cannot be accessed using the dl interface.
2426                  */
2427                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2428                 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
2429                 g_free (encoded);
2430         } else {
2431                 encode_value (jinfo->used_regs, p, &p);
2432         }
2433
2434         /* Exception table */
2435         if (header->num_clauses) {
2436                 for (k = 0; k < header->num_clauses; ++k) {
2437                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2438
2439                         encode_value (ei->exvar_offset, p, &p);
2440
2441                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2442                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2443
2444                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2445                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2446                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2447                 }
2448         }
2449
2450         if (jinfo->has_generic_jit_info) {
2451                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2452
2453                 encode_value (gi->has_this ? 1 : 0, p, &p);
2454                 encode_value (gi->this_reg, p, &p);
2455                 encode_value (gi->this_offset, p, &p);
2456
2457                 /* 
2458                  * Need to encode jinfo->method too, since it is not equal to 'method'
2459                  * when using generic sharing.
2460                  */
2461                 encode_method_ref (acfg, jinfo->method, p, &p);
2462         }
2463
2464         g_assert (debug_info_size < buf_size);
2465
2466         encode_value (debug_info_size, p, &p);
2467         if (debug_info_size) {
2468                 memcpy (p, debug_info, debug_info_size);
2469                 p += debug_info_size;
2470                 g_free (debug_info);
2471         }
2472
2473         acfg->stats.ex_info_size += p - buf;
2474
2475         /* Emit info */
2476
2477         emit_label (acfg, symbol);
2478
2479         g_assert (p - buf < buf_size);
2480         emit_bytes (acfg, buf, p - buf);
2481         g_free (buf);
2482 }
2483
2484 static void
2485 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2486 {
2487         MonoClass *klass = mono_class_get (acfg->image, token);
2488         guint8 *p, *buf;
2489         int i, buf_size;
2490         char symbol [128];
2491         gboolean no_special_static, cant_encode;
2492         gpointer iter = NULL;
2493
2494         buf_size = 10240 + (klass->vtable_size * 16);
2495         p = buf = g_malloc (buf_size);
2496
2497         g_assert (klass);
2498
2499         mono_class_init (klass);
2500
2501         mono_class_get_nested_types (klass, &iter);
2502         g_assert (klass->nested_classes_inited);
2503
2504         mono_class_setup_vtable (klass);
2505
2506         /* 
2507          * Emit all the information which is required for creating vtables so
2508          * the runtime does not need to create the MonoMethod structures which
2509          * take up a lot of space.
2510          */
2511
2512         no_special_static = !mono_class_has_special_static_fields (klass);
2513
2514         /* Check whenever we have enough info to encode the vtable */
2515         cant_encode = FALSE;
2516         for (i = 0; i < klass->vtable_size; ++i) {
2517                 MonoMethod *cm = klass->vtable [i];
2518
2519                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
2520                         cant_encode = TRUE;
2521         }
2522
2523         if (klass->generic_container || cant_encode) {
2524                 encode_value (-1, p, &p);
2525         } else {
2526                 encode_value (klass->vtable_size, p, &p);
2527                 encode_value ((no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | ((klass->ext && klass->ext->nested_classes) ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
2528                 if (klass->has_cctor)
2529                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2530                 if (klass->has_finalize)
2531                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2532  
2533                 encode_value (klass->instance_size, p, &p);
2534                 encode_value (mono_class_data_size (klass), p, &p);
2535                 encode_value (klass->packing_size, p, &p);
2536                 encode_value (klass->min_align, p, &p);
2537
2538                 for (i = 0; i < klass->vtable_size; ++i) {
2539                         MonoMethod *cm = klass->vtable [i];
2540
2541                         if (cm)
2542                                 encode_method_ref (acfg, cm, p, &p);
2543                         else
2544                                 encode_value (0, p, &p);
2545                 }
2546         }
2547
2548         acfg->stats.class_info_size += p - buf;
2549
2550         /* Emit the info */
2551         sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2552         emit_label (acfg, symbol);
2553
2554         g_assert (p - buf < buf_size);
2555         emit_bytes (acfg, buf, p - buf);
2556         g_free (buf);
2557 }
2558
2559 /*
2560  * Calls made from AOTed code are routed through a table of jumps similar to the
2561  * ELF PLT (Program Linkage Table). The differences are the following:
2562  * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2563  *   GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2564  *   jumps. This means the jumps need to be patched when the address of the callee is
2565  *   known. Initially the PLT entries jump to code which transfers control to the
2566  *   AOT runtime through the first PLT entry.
2567  */
2568 static void
2569 emit_plt (MonoAotCompile *acfg)
2570 {
2571         char symbol [128];
2572         int i;
2573
2574         emit_line (acfg);
2575         sprintf (symbol, "plt");
2576
2577         emit_section_change (acfg, ".text", 0);
2578         emit_global (acfg, symbol, TRUE);
2579 #ifdef TARGET_X86
2580         /* This section will be made read-write by the AOT loader */
2581         emit_alignment (acfg, mono_pagesize ());
2582 #else
2583         emit_alignment (acfg, 16);
2584 #endif
2585         emit_label (acfg, symbol);
2586
2587         for (i = 0; i < acfg->plt_offset; ++i) {
2588                 char label [128];
2589
2590                 sprintf (label, ".Lp_%d", i);
2591                 emit_label (acfg, label);
2592
2593                 /* 
2594                  * The first plt entry is used to transfer code to the AOT loader. 
2595                  */
2596                 arch_emit_plt_entry (acfg, i);
2597         }
2598
2599         sprintf (symbol, "plt_end");
2600         emit_global (acfg, symbol, TRUE);
2601         emit_label (acfg, symbol);
2602 }
2603
2604 static G_GNUC_UNUSED void
2605 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code, 
2606                                  guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
2607 {
2608         char symbol [256];
2609         guint32 buf_size;
2610         MonoJumpInfo *patch_info;
2611         guint8 *buf, *p;
2612         GPtrArray *patches;
2613
2614         /* Emit code */
2615
2616         sprintf (symbol, "%s", name);
2617
2618         emit_section_change (acfg, ".text", 0);
2619         emit_global (acfg, symbol, TRUE);
2620         emit_alignment (acfg, 16);
2621         emit_label (acfg, symbol);
2622
2623         sprintf (symbol, ".Lnamed_%s", name);
2624         emit_label (acfg, symbol);
2625
2626         /* 
2627          * The code should access everything through the GOT, so we pass
2628          * TRUE here.
2629          */
2630         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
2631
2632         /* Emit info */
2633
2634         /* Sort relocations */
2635         patches = g_ptr_array_new ();
2636         for (patch_info = ji; patch_info; patch_info = patch_info->next)
2637                 g_ptr_array_add (patches, patch_info);
2638         g_ptr_array_sort (patches, compare_patches);
2639
2640         buf_size = patches->len * 128 + 128;
2641         buf = g_malloc (buf_size);
2642         p = buf;
2643
2644         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
2645         g_assert (p - buf < buf_size);
2646
2647         sprintf (symbol, "%s_p", name);
2648
2649         emit_section_change (acfg, ".text", 0);
2650         emit_global (acfg, symbol, FALSE);
2651         emit_label (acfg, symbol);
2652                 
2653         emit_bytes (acfg, buf, p - buf);
2654
2655         /* Emit debug info */
2656         if (unwind_ops) {
2657                 char symbol2 [256];
2658
2659                 sprintf (symbol, "%s", name);
2660                 sprintf (symbol2, ".Lnamed_%s", name);
2661
2662                 if (acfg->dwarf)
2663                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
2664         }
2665 }
2666
2667 static void
2668 emit_trampolines (MonoAotCompile *acfg)
2669 {
2670         char symbol [256];
2671         int i, tramp_got_offset;
2672         MonoAotTrampoline ntype;
2673 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2674         int tramp_type;
2675         guint32 code_size;
2676         MonoJumpInfo *ji;
2677         guint8 *code;
2678         GSList *unwind_ops;
2679 #endif
2680
2681         if (!acfg->aot_opts.full_aot)
2682                 return;
2683         
2684         g_assert (acfg->image->assembly);
2685
2686         /* Currently, we only emit most trampolines into the mscorlib AOT image. */
2687         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2688 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2689                 /*
2690                  * Emit the generic trampolines.
2691                  *
2692                  * We could save some code by treating the generic trampolines as a wrapper
2693                  * method, but that approach has its own complexities, so we choose the simpler
2694                  * method.
2695                  */
2696                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
2697                         code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
2698
2699                         /* Emit trampoline code */
2700
2701                         sprintf (symbol, "generic_trampoline_%d", tramp_type);
2702
2703                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
2704                 }
2705
2706                 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
2707                 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
2708 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
2709                 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
2710                 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2711                 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
2712                 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2713 #endif
2714
2715                 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
2716                 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2717
2718                 /* Emit the exception related code pieces */
2719                 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
2720                 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
2721                 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
2722                 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
2723                 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
2724                 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
2725                 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
2726                 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
2727                 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
2728                 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
2729                 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
2730                 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
2731
2732 #if defined(TARGET_AMD64)
2733                 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
2734                 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
2735 #endif
2736
2737 #if defined(TARGET_AMD64) || defined(TARGET_ARM)
2738                 for (i = 0; i < 128; ++i) {
2739                         int offset;
2740
2741                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
2742                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2743                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2744                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2745
2746                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
2747                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2748                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2749                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2750                 }
2751 #endif
2752
2753 #if defined(TARGET_AMD64) || defined(TARGET_ARM)
2754                 {
2755                         GSList *l;
2756
2757                         /* delegate_invoke_impl trampolines */
2758                         l = mono_arch_get_delegate_invoke_impls ();
2759                         while (l) {
2760                                 MonoAotTrampInfo *info = l->data;
2761
2762                                 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
2763                                 l = l->next;
2764                         }
2765                 }
2766 #endif
2767
2768 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
2769
2770                 /* Emit trampolines which are numerous */
2771
2772                 /*
2773                  * These include the following:
2774                  * - specific trampolines
2775                  * - static rgctx invoke trampolines
2776                  * - imt thunks
2777                  * These trampolines have the same code, they are parameterized by GOT 
2778                  * slots. 
2779                  * They are defined in this file, in the arch_... routines instead of
2780                  * in tramp-<ARCH>.c, since it is easier to do it this way.
2781                  */
2782
2783                 /*
2784                  * When running in aot-only mode, we can't create specific trampolines at 
2785                  * runtime, so we create a few, and save them in the AOT file. 
2786                  * Normal trampolines embed their argument as a literal inside the 
2787                  * trampoline code, we can't do that here, so instead we embed an offset
2788                  * which needs to be added to the trampoline address to get the address of
2789                  * the GOT slot which contains the argument value.
2790                  * The generated trampolines jump to the generic trampolines using another
2791                  * GOT slot, which will be setup by the AOT loader to point to the 
2792                  * generic trampoline code of the given type.
2793                  */
2794
2795                 /*
2796                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
2797                  * each class).
2798                  */
2799
2800                 emit_section_change (acfg, ".text", 0);
2801
2802                 tramp_got_offset = acfg->got_offset;
2803
2804                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
2805                         switch (ntype) {
2806                         case MONO_AOT_TRAMP_SPECIFIC:
2807                                 sprintf (symbol, "specific_trampolines");
2808                                 break;
2809                         case MONO_AOT_TRAMP_STATIC_RGCTX:
2810                                 sprintf (symbol, "static_rgctx_trampolines");
2811                                 break;
2812                         case MONO_AOT_TRAMP_IMT_THUNK:
2813                                 sprintf (symbol, "imt_thunks");
2814                                 break;
2815                         default:
2816                                 g_assert_not_reached ();
2817                         }
2818
2819                         emit_global (acfg, symbol, TRUE);
2820                         emit_alignment (acfg, 16);
2821                         emit_label (acfg, symbol);
2822
2823                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
2824
2825                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
2826                                 int tramp_size = 0;
2827
2828                                 switch (ntype) {
2829                                 case MONO_AOT_TRAMP_SPECIFIC:
2830                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
2831                                         tramp_got_offset += 2;
2832                                 break;
2833                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
2834                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
2835                                         tramp_got_offset += 2;
2836                                         break;
2837                                 case MONO_AOT_TRAMP_IMT_THUNK:
2838                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
2839                                         tramp_got_offset += 1;
2840                                         break;
2841                                 default:
2842                                         g_assert_not_reached ();
2843                                 }
2844
2845                                 if (!acfg->trampoline_size [ntype]) {
2846                                         g_assert (tramp_size);
2847                                         acfg->trampoline_size [ntype] = tramp_size;
2848                                 }
2849                         }
2850                 }
2851
2852                 /* Reserve some entries at the end of the GOT for our use */
2853                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
2854         }
2855
2856         /* Unbox trampolines */
2857         for (i = 0; i < acfg->methods->len; ++i) {
2858                 MonoMethod *method = g_ptr_array_index (acfg->methods, i);
2859                 MonoCompile *cfg;
2860                 char call_target [256];
2861
2862                 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
2863                 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2864                         continue;
2865
2866                 if (!method->wrapper_type && !method->is_inflated) {
2867                         g_assert (method->token);
2868                         sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2869                 } else {
2870                         sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2871                 }
2872
2873                 emit_section_change (acfg, ".text", 0);
2874                 emit_global (acfg, symbol, TRUE);
2875                 emit_label (acfg, symbol);
2876
2877                 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
2878
2879                 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2880         }
2881
2882         acfg->got_offset += acfg->num_trampoline_got_entries;
2883 }
2884
2885 static gboolean
2886 str_begins_with (const char *str1, const char *str2)
2887 {
2888         int len = strlen (str2);
2889         return strncmp (str1, str2, len) == 0;
2890 }
2891
2892 static void
2893 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
2894 {
2895         gchar **args, **ptr;
2896
2897         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
2898         for (ptr = args; ptr && *ptr; ptr ++) {
2899                 const char *arg = *ptr;
2900
2901                 if (str_begins_with (arg, "outfile=")) {
2902                         opts->outfile = g_strdup (arg + strlen ("outfile="));
2903                 } else if (str_begins_with (arg, "save-temps")) {
2904                         opts->save_temps = TRUE;
2905                 } else if (str_begins_with (arg, "keep-temps")) {
2906                         opts->save_temps = TRUE;
2907                 } else if (str_begins_with (arg, "write-symbols")) {
2908                         opts->write_symbols = TRUE;
2909                 } else if (str_begins_with (arg, "metadata-only")) {
2910                         opts->metadata_only = TRUE;
2911                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
2912                         opts->bind_to_runtime_version = TRUE;
2913                 } else if (str_begins_with (arg, "full")) {
2914                         opts->full_aot = TRUE;
2915                 } else if (str_begins_with (arg, "threads=")) {
2916                         opts->nthreads = atoi (arg + strlen ("threads="));
2917                 } else if (str_begins_with (arg, "static")) {
2918                         opts->static_link = TRUE;
2919                         opts->no_dlsym = TRUE;
2920                 } else if (str_begins_with (arg, "asmonly")) {
2921                         opts->asm_only = TRUE;
2922                 } else if (str_begins_with (arg, "asmwriter")) {
2923                         opts->asm_writer = TRUE;
2924                 } else if (str_begins_with (arg, "nodebug")) {
2925                         opts->nodebug = TRUE;
2926                 } else if (str_begins_with (arg, "ntrampolines=")) {
2927                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
2928                 } else {
2929                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
2930                         exit (1);
2931                 }
2932         }
2933
2934         g_strfreev (args);
2935 }
2936
2937 static void
2938 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
2939 {
2940         MonoMethod *method = (MonoMethod*)key;
2941         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
2942         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
2943         MonoAotCompile *acfg = user_data;
2944
2945         new_ji->image = ji->image;
2946         new_ji->token = ji->token;
2947         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
2948 }
2949
2950 static gboolean
2951 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
2952 {
2953         if (klass->type_token)
2954                 return TRUE;
2955         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2956                 return TRUE;
2957         if (klass->rank)
2958                 return can_encode_class (acfg, klass->element_class);
2959         return FALSE;
2960 }
2961
2962 static gboolean
2963 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2964 {
2965         switch (patch_info->type) {
2966         case MONO_PATCH_INFO_METHOD:
2967         case MONO_PATCH_INFO_METHODCONST: {
2968                 MonoMethod *method = patch_info->data.method;
2969
2970                 if (method->wrapper_type) {
2971                         switch (method->wrapper_type) {
2972                         case MONO_WRAPPER_NONE:
2973                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2974                         case MONO_WRAPPER_XDOMAIN_INVOKE:
2975                         case MONO_WRAPPER_STFLD:
2976                         case MONO_WRAPPER_LDFLD:
2977                         case MONO_WRAPPER_LDFLDA:
2978                         case MONO_WRAPPER_LDFLD_REMOTE:
2979                         case MONO_WRAPPER_STFLD_REMOTE:
2980                         case MONO_WRAPPER_STELEMREF:
2981                         case MONO_WRAPPER_ISINST:
2982                         case MONO_WRAPPER_PROXY_ISINST:
2983                         case MONO_WRAPPER_ALLOC:
2984                         case MONO_WRAPPER_REMOTING_INVOKE:
2985                         case MONO_WRAPPER_UNKNOWN:
2986                                 break;
2987                         default:
2988                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
2989                                 return FALSE;
2990                         }
2991                 } else {
2992                         if (!method->token) {
2993                                 /* The method is part of a constructed type like Int[,].Set (). */
2994                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
2995                                         if (method->klass->rank)
2996                                                 return TRUE;
2997                                         return FALSE;
2998                                 }
2999                         }
3000                 }
3001                 break;
3002         }
3003         case MONO_PATCH_INFO_VTABLE:
3004         case MONO_PATCH_INFO_CLASS_INIT:
3005         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3006         case MONO_PATCH_INFO_CLASS:
3007         case MONO_PATCH_INFO_IID:
3008         case MONO_PATCH_INFO_ADJUSTED_IID:
3009                 if (!can_encode_class (acfg, patch_info->data.klass)) {
3010                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
3011                         return FALSE;
3012                 }
3013                 break;
3014         case MONO_PATCH_INFO_RGCTX_FETCH: {
3015                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3016
3017                 if (!can_encode_patch (acfg, entry->data))
3018                         return FALSE;
3019                 break;
3020         }
3021         default:
3022                 break;
3023         }
3024
3025         return TRUE;
3026 }
3027
3028 static void
3029 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
3030
3031 /*
3032  * compile_method:
3033  *
3034  *   AOT compile a given method.
3035  * This function might be called by multiple threads, so it must be thread-safe.
3036  */
3037 static void
3038 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3039 {
3040         MonoCompile *cfg;
3041         MonoJumpInfo *patch_info;
3042         gboolean skip;
3043         int index;
3044         MonoMethod *wrapped;
3045
3046         if (acfg->aot_opts.metadata_only)
3047                 return;
3048
3049         mono_acfg_lock (acfg);
3050         index = get_method_index (acfg, method);
3051         mono_acfg_unlock (acfg);
3052
3053         /* fixme: maybe we can also precompile wrapper methods */
3054         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3055                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3056                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3057                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3058                 return;
3059         }
3060
3061         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3062                 return;
3063
3064         wrapped = mono_marshal_method_from_wrapper (method);
3065         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3066                 // FIXME: The wrapper should be generic too, but it is not
3067                 return;
3068
3069         InterlockedIncrement (&acfg->stats.mcount);
3070
3071 #if 0
3072         if (method->is_generic || method->klass->generic_container) {
3073                 InterlockedIncrement (&acfg->stats.genericcount);
3074                 return;
3075         }
3076 #endif
3077
3078         //acfg->aot_opts.print_skipped_methods = TRUE;
3079
3080         /*
3081          * Since these methods are the only ones which are compiled with
3082          * AOT support, and they are not used by runtime startup/shutdown code,
3083          * the runtime will not see AOT methods during AOT compilation,so it
3084          * does not need to support them by creating a fake GOT etc.
3085          */
3086         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3087         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3088                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3089                 InterlockedIncrement (&acfg->stats.genericcount);
3090                 return;
3091         }
3092         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3093                 /* Let the exception happen at runtime */
3094                 return;
3095         }
3096
3097         if (cfg->disable_aot) {
3098                 if (acfg->aot_opts.print_skipped_methods)
3099                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3100                 InterlockedIncrement (&acfg->stats.ocount);
3101                 mono_destroy_compile (cfg);
3102                 return;
3103         }
3104
3105         /* Nullify patches which need no aot processing */
3106         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3107                 switch (patch_info->type) {
3108                 case MONO_PATCH_INFO_LABEL:
3109                 case MONO_PATCH_INFO_BB:
3110                         patch_info->type = MONO_PATCH_INFO_NONE;
3111                         break;
3112                 default:
3113                         break;
3114                 }
3115         }
3116
3117         /* Collect method->token associations from the cfg */
3118         mono_acfg_lock (acfg);
3119         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3120         mono_acfg_unlock (acfg);
3121
3122         /*
3123          * Check for absolute addresses.
3124          */
3125         skip = FALSE;
3126         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3127                 switch (patch_info->type) {
3128                 case MONO_PATCH_INFO_ABS:
3129                         /* unable to handle this */
3130                         skip = TRUE;    
3131                         break;
3132                 default:
3133                         break;
3134                 }
3135         }
3136
3137         if (skip) {
3138                 if (acfg->aot_opts.print_skipped_methods)
3139                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
3140                 InterlockedIncrement (&acfg->stats.abscount);
3141                 mono_destroy_compile (cfg);
3142                 return;
3143         }
3144
3145         /* Lock for the rest of the code */
3146         mono_acfg_lock (acfg);
3147
3148         /*
3149          * Check for methods/klasses we can't encode.
3150          */
3151         skip = FALSE;
3152         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3153                 if (!can_encode_patch (acfg, patch_info))
3154                         skip = TRUE;
3155         }
3156
3157         if (skip) {
3158                 if (acfg->aot_opts.print_skipped_methods)
3159                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
3160                 acfg->stats.ocount++;
3161                 mono_destroy_compile (cfg);
3162                 mono_acfg_unlock (acfg);
3163                 return;
3164         }
3165
3166         /* Adds generic instances referenced by this method */
3167         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3168                 switch (patch_info->type) {
3169                 case MONO_PATCH_INFO_METHOD: {
3170                         MonoMethod *m = patch_info->data.method;
3171                         if (m->is_inflated) {
3172                                 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3173                                           mono_method_is_generic_sharable_impl (m, FALSE)) &&
3174                                         !method_has_type_vars (m)) {
3175                                         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3176                                                 if (acfg->aot_opts.full_aot)
3177                                                         add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
3178                                         } else {
3179                                                 add_extra_method (acfg, m);
3180                                         }
3181                                 }
3182                                 add_generic_class (acfg, m->klass);
3183                         }
3184                         break;
3185                 }
3186                 default:
3187                         break;
3188                 }
3189         }
3190
3191         /* Determine whenever the method has GOT slots */
3192         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3193                 switch (patch_info->type) {
3194                 case MONO_PATCH_INFO_GOT_OFFSET:
3195                 case MONO_PATCH_INFO_NONE:
3196                         break;
3197                 case MONO_PATCH_INFO_IMAGE:
3198                         /* The assembly is stored in GOT slot 0 */
3199                         if (patch_info->data.image != acfg->image)
3200                                 cfg->has_got_slots = TRUE;
3201                         break;
3202                 default:
3203                         if (!is_plt_patch (patch_info))
3204                                 cfg->has_got_slots = TRUE;
3205                         break;
3206                 }
3207         }
3208
3209         if (!cfg->has_got_slots)
3210                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3211
3212         /* Make a copy of the patch info which is in the mempool */
3213         {
3214                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3215
3216                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3217                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3218
3219                         if (!patches)
3220                                 patches = new_patch_info;
3221                         else
3222                                 patches_end->next = new_patch_info;
3223                         patches_end = new_patch_info;
3224                 }
3225                 cfg->patch_info = patches;
3226         }
3227         /* Make a copy of the unwind info */
3228         {
3229                 GSList *l, *unwind_ops;
3230                 MonoUnwindOp *op;
3231
3232                 unwind_ops = NULL;
3233                 for (l = cfg->unwind_ops; l; l = l->next) {
3234                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
3235                         memcpy (op, l->data, sizeof (MonoUnwindOp));
3236                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
3237                 }
3238                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
3239         }
3240         /* Make a copy of the argument/local info */
3241         {
3242                 MonoInst **args, **locals;
3243                 MonoMethodSignature *sig;
3244                 MonoMethodHeader *header;
3245                 int i;
3246                 
3247                 sig = mono_method_signature (method);
3248                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
3249                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3250                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3251                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
3252                 }
3253                 cfg->args = args;
3254
3255                 header = mono_method_get_header (method);
3256                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
3257                 for (i = 0; i < header->num_locals; ++i) {
3258                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3259                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
3260                 }
3261                 cfg->locals = locals;
3262         }
3263
3264         /* Free some fields used by cfg to conserve memory */
3265         mono_mempool_destroy (cfg->mempool);
3266         cfg->mempool = NULL;
3267         g_free (cfg->varinfo);
3268         cfg->varinfo = NULL;
3269         g_free (cfg->vars);
3270         cfg->vars = NULL;
3271         if (cfg->rs) {
3272                 mono_regstate_free (cfg->rs);
3273                 cfg->rs = NULL;
3274         }
3275
3276         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
3277
3278         while (index >= acfg->cfgs_size) {
3279                 MonoCompile **new_cfgs;
3280                 int new_size;
3281
3282                 new_size = acfg->cfgs_size * 2;
3283                 new_cfgs = g_new0 (MonoCompile*, new_size);
3284                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3285                 g_free (acfg->cfgs);
3286                 acfg->cfgs = new_cfgs;
3287                 acfg->cfgs_size = new_size;
3288         }
3289         acfg->cfgs [index] = cfg;
3290
3291         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3292
3293         /*
3294         if (cfg->orig_method->wrapper_type)
3295                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3296         */
3297
3298         mono_acfg_unlock (acfg);
3299
3300         InterlockedIncrement (&acfg->stats.ccount);
3301 }
3302  
3303 static void
3304 compile_thread_main (gpointer *user_data)
3305 {
3306         MonoDomain *domain = user_data [0];
3307         MonoAotCompile *acfg = user_data [1];
3308         GPtrArray *methods = user_data [2];
3309         int i;
3310
3311         mono_thread_attach (domain);
3312
3313         for (i = 0; i < methods->len; ++i)
3314                 compile_method (acfg, g_ptr_array_index (methods, i));
3315 }
3316
3317 static void
3318 load_profile_files (MonoAotCompile *acfg)
3319 {
3320         FILE *infile;
3321         char *tmp;
3322         int file_index, res, method_index, i;
3323         char ver [256];
3324         guint32 token;
3325         GList *unordered;
3326
3327         file_index = 0;
3328         while (TRUE) {
3329                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%s-%d", g_get_home_dir (), acfg->image->assembly_name, acfg->image->guid, file_index);
3330
3331                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3332                         g_free (tmp);
3333                         break;
3334                 }
3335
3336                 infile = fopen (tmp, "r");
3337                 g_assert (infile);
3338
3339                 printf ("Using profile data file '%s'\n", tmp);
3340                 g_free (tmp);
3341
3342                 file_index ++;
3343
3344                 res = fscanf (infile, "%32s\n", ver);
3345                 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3346                         printf ("Profile file has wrong version or invalid.\n");
3347                         fclose (infile);
3348                         continue;
3349                 }
3350
3351                 while (TRUE) {
3352                         res = fscanf (infile, "%d\n", &token);
3353                         if (res < 1)
3354                                 break;
3355
3356                         method_index = mono_metadata_token_index (token) - 1;
3357
3358                         if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3359                                 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3360                 }
3361                 fclose (infile);
3362         }
3363
3364         /* Add missing methods */
3365         unordered = NULL;
3366         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3367                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3368                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3369         }
3370         unordered = g_list_reverse (unordered);
3371         if (acfg->method_order)
3372                 g_list_last (acfg->method_order)->next = unordered;
3373         else
3374                 acfg->method_order = unordered;
3375 }
3376
3377 static void
3378 emit_code (MonoAotCompile *acfg)
3379 {
3380         int i;
3381         char symbol [256];
3382         GList *l;
3383
3384         sprintf (symbol, "methods");
3385         emit_section_change (acfg, ".text", 0);
3386         emit_global (acfg, symbol, TRUE);
3387         emit_alignment (acfg, 8);
3388         emit_label (acfg, symbol);
3389
3390         /* 
3391          * Emit some padding so the local symbol for the first method doesn't have the
3392          * same address as 'methods'.
3393          */
3394         emit_zero_bytes (acfg, 16);
3395
3396         for (l = acfg->method_order; l != NULL; l = l->next) {
3397                 i = GPOINTER_TO_UINT (l->data);
3398
3399                 if (acfg->cfgs [i])
3400                         emit_method_code (acfg, acfg->cfgs [i]);
3401         }
3402
3403         sprintf (symbol, "methods_end");
3404         emit_section_change (acfg, ".text", 0);
3405         emit_global (acfg, symbol, FALSE);
3406         emit_alignment (acfg, 8);
3407         emit_label (acfg, symbol);
3408
3409         sprintf (symbol, "method_offsets");
3410         emit_section_change (acfg, ".text", 1);
3411         emit_global (acfg, symbol, FALSE);
3412         emit_alignment (acfg, 8);
3413         emit_label (acfg, symbol);
3414
3415         for (i = 0; i < acfg->nmethods; ++i) {
3416                 if (acfg->cfgs [i]) {
3417                         sprintf (symbol, ".Lm_%x", i);
3418                         emit_symbol_diff (acfg, symbol, "methods", 0);
3419                 } else {
3420                         emit_int32 (acfg, 0xffffffff);
3421                 }
3422         }
3423         emit_line (acfg);
3424 }
3425
3426 static void
3427 emit_info (MonoAotCompile *acfg)
3428 {
3429         int i;
3430         char symbol [256];
3431         GList *l;
3432
3433         /* Emit method info */
3434         sprintf (symbol, "method_info");
3435         emit_section_change (acfg, ".text", 1);
3436         emit_global (acfg, symbol, FALSE);
3437         emit_alignment (acfg, 8);
3438         emit_label (acfg, symbol);
3439
3440         /* To reduce size of generated assembly code */
3441         sprintf (symbol, "mi");
3442         emit_label (acfg, symbol);
3443
3444         for (l = acfg->method_order; l != NULL; l = l->next) {
3445                 i = GPOINTER_TO_UINT (l->data);
3446
3447                 if (acfg->cfgs [i])
3448                         emit_method_info (acfg, acfg->cfgs [i]);
3449         }
3450
3451         sprintf (symbol, "method_info_offsets");
3452         emit_section_change (acfg, ".text", 1);
3453         emit_global (acfg, symbol, FALSE);
3454         emit_alignment (acfg, 8);
3455         emit_label (acfg, symbol);
3456
3457         for (i = 0; i < acfg->nmethods; ++i) {
3458                 if (acfg->cfgs [i]) {
3459                         sprintf (symbol, ".Lm_%x_p", i);
3460                         emit_symbol_diff (acfg, symbol, "mi", 0);
3461                 } else {
3462                         emit_int32 (acfg, 0);
3463                 }
3464         }
3465         emit_line (acfg);
3466 }
3467
3468 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
3469
3470 /*
3471  * mono_aot_str_hash:
3472  *
3473  * Hash function for strings which we use to hash strings for things which are
3474  * saved in the AOT image, since g_str_hash () can change.
3475  */
3476 guint
3477 mono_aot_str_hash (gconstpointer v1)
3478 {
3479         /* Same as g_str_hash () in glib */
3480         char *p = (char *) v1;
3481         guint hash = *p;
3482
3483         while (*p++) {
3484                 if (*p)
3485                         hash = (hash << 5) - hash + *p;
3486         }
3487
3488         return hash;
3489
3490
3491 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
3492 #define mix(a,b,c) { \
3493         a -= c;  a ^= rot(c, 4);  c += b; \
3494         b -= a;  b ^= rot(a, 6);  a += c; \
3495         c -= b;  c ^= rot(b, 8);  b += a; \
3496         a -= c;  a ^= rot(c,16);  c += b; \
3497         b -= a;  b ^= rot(a,19);  a += c; \
3498         c -= b;  c ^= rot(b, 4);  b += a; \
3499 }
3500 #define final(a,b,c) { \
3501         c ^= b; c -= rot(b,14); \
3502         a ^= c; a -= rot(c,11); \
3503         b ^= a; b -= rot(a,25); \
3504         c ^= b; c -= rot(b,16); \
3505         a ^= c; a -= rot(c,4);  \
3506         b ^= a; b -= rot(a,14); \
3507         c ^= b; c -= rot(b,24); \
3508 }
3509
3510 static guint
3511 mono_aot_type_hash (MonoType *t1)
3512 {
3513         guint hash = t1->type;
3514
3515         hash |= t1->byref << 6; /* do not collide with t1->type values */
3516         switch (t1->type) {
3517         case MONO_TYPE_VALUETYPE:
3518         case MONO_TYPE_CLASS:
3519         case MONO_TYPE_SZARRAY:
3520                 /* check if the distribution is good enough */
3521                 return ((hash << 5) - hash) ^ mono_aot_str_hash (t1->data.klass->name);
3522         case MONO_TYPE_PTR:
3523                 return ((hash << 5) - hash) ^ mono_aot_type_hash (t1->data.type);
3524         case MONO_TYPE_ARRAY:
3525                 return ((hash << 5) - hash) ^ mono_aot_type_hash (&t1->data.array->eklass->byval_arg);
3526         case MONO_TYPE_GENERICINST:
3527                 return ((hash << 5) - hash) ^ 0;
3528         }
3529         return hash;
3530 }
3531
3532 /*
3533  * mono_aot_method_hash:
3534  *
3535  *   Return a hash code for methods which only depends on metadata.
3536  */
3537 guint32
3538 mono_aot_method_hash (MonoMethod *method)
3539 {
3540         MonoMethodSignature *sig;
3541         MonoClass *klass;
3542         int i;
3543         int hashes_count;
3544         guint32 *hashes_start, *hashes;
3545         guint32 a, b, c;
3546
3547         /* Similar to the hash in mono_method_get_imt_slot () */
3548
3549         sig = mono_method_signature (method);
3550
3551         hashes_count = sig->param_count + 5;
3552         hashes_start = malloc (hashes_count * sizeof (guint32));
3553         hashes = hashes_start;
3554
3555         /* Some wrappers are assigned to random classes */
3556         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3557                 klass = method->klass;
3558         else
3559                 klass = mono_defaults.object_class;
3560
3561         if (!method->wrapper_type) {
3562                 char *full_name = mono_type_full_name (&klass->byval_arg);
3563
3564                 hashes [0] = mono_aot_str_hash (full_name);
3565                 hashes [1] = 0;
3566                 g_free (full_name);
3567         } else {
3568                 hashes [0] = mono_aot_str_hash (klass->name);
3569                 hashes [1] = mono_aot_str_hash (klass->name_space);
3570         }
3571         hashes [2] = mono_aot_str_hash (method->name);
3572         hashes [3] = method->wrapper_type;
3573         hashes [4] = mono_aot_type_hash (sig->ret);
3574         for (i = 0; i < sig->param_count; i++) {
3575                 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
3576         }
3577         
3578         /* Setup internal state */
3579         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
3580
3581         /* Handle most of the hashes */
3582         while (hashes_count > 3) {
3583                 a += hashes [0];
3584                 b += hashes [1];
3585                 c += hashes [2];
3586                 mix (a,b,c);
3587                 hashes_count -= 3;
3588                 hashes += 3;
3589         }
3590
3591         /* Handle the last 3 hashes (all the case statements fall through) */
3592         switch (hashes_count) { 
3593         case 3 : c += hashes [2];
3594         case 2 : b += hashes [1];
3595         case 1 : a += hashes [0];
3596                 final (a,b,c);
3597         case 0: /* nothing left to add */
3598                 break;
3599         }
3600         
3601         free (hashes_start);
3602         
3603         return c;
3604 }
3605 #undef rot
3606 #undef mix
3607 #undef final
3608
3609 /*
3610  * mono_aot_wrapper_name:
3611  *
3612  *   Return a string which uniqely identifies the given wrapper method.
3613  */
3614 char*
3615 mono_aot_wrapper_name (MonoMethod *method)
3616 {
3617         char *name, *tmpsig, *klass_desc;
3618
3619         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3620
3621         switch (method->wrapper_type) {
3622         case MONO_WRAPPER_RUNTIME_INVOKE:
3623         case MONO_WRAPPER_DELEGATE_INVOKE:
3624         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3625         case MONO_WRAPPER_DELEGATE_END_INVOKE:
3626                 /* This is a hack to work around the fact that runtime invoke wrappers get assigned to some random class */
3627                 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
3628                 break;
3629         default:
3630                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
3631
3632                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
3633                 break;
3634         }
3635
3636         g_free (tmpsig);
3637
3638         return name;
3639 }
3640
3641 /*
3642  * mono_aot_tramp_info_create:
3643  *
3644  *   Create a MonoAotTrampInfo structure from the arguments.
3645  */
3646 MonoAotTrampInfo*
3647 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
3648 {
3649         MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
3650
3651         info->name = (char*)name;
3652         info->code = code;
3653         info->code_size = code_size;
3654
3655         return info;
3656 }
3657
3658 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
3659
3660 typedef struct HashEntry {
3661     guint32 key, value, index;
3662         struct HashEntry *next;
3663 } HashEntry;
3664
3665 /*
3666  * emit_extra_methods:
3667  *
3668  * Emit methods which are not in the METHOD table, like wrappers.
3669  */
3670 static void
3671 emit_extra_methods (MonoAotCompile *acfg)
3672 {
3673         int i, table_size, buf_size;
3674         char symbol [256];
3675         guint8 *p, *buf;
3676         guint32 *info_offsets;
3677         guint32 hash;
3678         GPtrArray *table;
3679         HashEntry *entry, *new_entry;
3680         int nmethods, max_chain_length;
3681         int *chain_lengths;
3682
3683         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
3684
3685         buf_size = acfg->extra_methods->len * 256 + 256;
3686         p = buf = g_malloc (buf_size);
3687
3688         /* Encode method info */
3689         nmethods = 0;
3690         /* So offsets are > 0 */
3691         *p = 0;
3692         p++;
3693         for (i = 0; i < acfg->extra_methods->len; ++i) {
3694                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3695                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3696                 char *name;
3697
3698                 if (!cfg)
3699                         continue;
3700
3701                 nmethods ++;
3702                 info_offsets [i] = p - buf;
3703
3704                 name = NULL;
3705                 if (method->wrapper_type) {
3706                         /* 
3707                          * We encode some wrappers using their name, since encoding them
3708                          * directly would be difficult. This also avoids creating the wrapper
3709                          * methods at runtime, since they are not needed anyway.
3710                          */
3711                         switch (method->wrapper_type) {
3712                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3713                         case MONO_WRAPPER_SYNCHRONIZED:
3714                                 /* encode_method_ref () can handle these */
3715                                 break;
3716                         case MONO_WRAPPER_RUNTIME_INVOKE:
3717                                 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
3718                                         /* Direct wrapper, encode normally */
3719                                         break;
3720                                 /* Fall through */
3721                         default:
3722                                 name = mono_aot_wrapper_name (method);
3723                                 break;
3724                         }
3725                 }
3726
3727                 if (name) {
3728                         encode_value (1, p, &p);
3729                         encode_value (method->wrapper_type, p, &p);
3730                         strcpy ((char*)p, name);
3731                         p += strlen (name ) + 1;
3732                         g_free (name);
3733                 } else {
3734                         encode_value (0, p, &p);
3735                         encode_method_ref (acfg, method, p, &p);
3736                 }
3737
3738                 g_assert ((p - buf) < buf_size);
3739         }
3740
3741         g_assert ((p - buf) < buf_size);
3742
3743         /* Emit method info */
3744         sprintf (symbol, "extra_method_info");
3745         emit_section_change (acfg, ".text", 1);
3746         emit_global (acfg, symbol, FALSE);
3747         emit_alignment (acfg, 8);
3748         emit_label (acfg, symbol);
3749
3750         emit_bytes (acfg, buf, p - buf);
3751
3752         emit_line (acfg);
3753
3754         /*
3755          * Construct a chained hash table for mapping indexes in extra_method_info to
3756          * method indexes.
3757          */
3758         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
3759         table = g_ptr_array_sized_new (table_size);
3760         for (i = 0; i < table_size; ++i)
3761                 g_ptr_array_add (table, NULL);
3762         chain_lengths = g_new0 (int, table_size);
3763         max_chain_length = 0;
3764         for (i = 0; i < acfg->extra_methods->len; ++i) {
3765                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3766                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3767                 guint32 key, value;
3768
3769                 if (!cfg)
3770                         continue;
3771
3772                 key = info_offsets [i];
3773                 value = get_method_index (acfg, method);
3774
3775                 hash = mono_aot_method_hash (method) % table_size;
3776
3777                 chain_lengths [hash] ++;
3778                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
3779
3780                 /* FIXME: Allocate from the mempool */
3781                 new_entry = g_new0 (HashEntry, 1);
3782                 new_entry->key = key;
3783                 new_entry->value = value;
3784
3785                 entry = g_ptr_array_index (table, hash);
3786                 if (entry == NULL) {
3787                         new_entry->index = hash;
3788                         g_ptr_array_index (table, hash) = new_entry;
3789                 } else {
3790                         while (entry->next)
3791                                 entry = entry->next;
3792                         
3793                         entry->next = new_entry;
3794                         new_entry->index = table->len;
3795                         g_ptr_array_add (table, new_entry);
3796                 }
3797         }
3798
3799         //printf ("MAX: %d\n", max_chain_length);
3800
3801         /* Emit the table */
3802         sprintf (symbol, "extra_method_table");
3803         emit_section_change (acfg, ".text", 0);
3804         emit_global (acfg, symbol, FALSE);
3805         emit_alignment (acfg, 8);
3806         emit_label (acfg, symbol);
3807
3808         g_assert (table_size < 65000);
3809         emit_int32 (acfg, table_size);
3810         g_assert (table->len < 65000);
3811         for (i = 0; i < table->len; ++i) {
3812                 HashEntry *entry = g_ptr_array_index (table, i);
3813
3814                 if (entry == NULL) {
3815                         emit_int32 (acfg, 0);
3816                         emit_int32 (acfg, 0);
3817                         emit_int32 (acfg, 0);
3818                 } else {
3819                         g_assert (entry->key > 0);
3820                         emit_int32 (acfg, entry->key);
3821                         emit_int32 (acfg, entry->value);
3822                         if (entry->next)
3823                                 emit_int32 (acfg, entry->next->index);
3824                         else
3825                                 emit_int32 (acfg, 0);
3826                 }
3827         }
3828
3829         /* 
3830          * Emit a table reverse mapping method indexes to their index in extra_method_info.
3831          * This is used by mono_aot_find_jit_info ().
3832          */
3833         sprintf (symbol, "extra_method_info_offsets");
3834         emit_section_change (acfg, ".text", 0);
3835         emit_global (acfg, symbol, FALSE);
3836         emit_alignment (acfg, 8);
3837         emit_label (acfg, symbol);
3838
3839         emit_int32 (acfg, acfg->extra_methods->len);
3840         for (i = 0; i < acfg->extra_methods->len; ++i) {
3841                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3842
3843                 emit_int32 (acfg, get_method_index (acfg, method));
3844                 emit_int32 (acfg, info_offsets [i]);
3845         }
3846 }       
3847
3848 static void
3849 emit_method_order (MonoAotCompile *acfg)
3850 {
3851         int i, index, len;
3852         char symbol [256];
3853         GList *l;
3854
3855         sprintf (symbol, "method_order");
3856         emit_section_change (acfg, ".text", 1);
3857         emit_global (acfg, symbol, FALSE);
3858         emit_alignment (acfg, 8);
3859         emit_label (acfg, symbol);
3860
3861         /* First emit an index table */
3862         index = 0;
3863         len = 0;
3864         for (l = acfg->method_order; l != NULL; l = l->next) {
3865                 i = GPOINTER_TO_UINT (l->data);
3866
3867                 if (acfg->cfgs [i]) {
3868                         if ((index % 1024) == 0) {
3869                                 emit_int32 (acfg, i);
3870                         }
3871
3872                         index ++;
3873                 }
3874
3875                 len ++;
3876         }
3877         emit_int32 (acfg, 0xffffff);
3878
3879         /* Then emit the whole method order */
3880         for (l = acfg->method_order; l != NULL; l = l->next) {
3881                 i = GPOINTER_TO_UINT (l->data);
3882
3883                 if (acfg->cfgs [i]) {
3884                         emit_int32 (acfg, i);
3885                 }
3886         }       
3887         emit_line (acfg);
3888
3889         sprintf (symbol, "method_order_end");
3890         emit_section_change (acfg, ".text", 1);
3891         emit_global (acfg, symbol, FALSE);
3892         emit_label (acfg, symbol);
3893 }
3894
3895 static void
3896 emit_exception_info (MonoAotCompile *acfg)
3897 {
3898         int i;
3899         char symbol [256];
3900
3901         sprintf (symbol, "ex_info");
3902         emit_section_change (acfg, ".text", 1);
3903         emit_global (acfg, symbol, FALSE);
3904         emit_alignment (acfg, 8);
3905         emit_label (acfg, symbol);
3906
3907         /* To reduce size of generated assembly */
3908         sprintf (symbol, "ex");
3909         emit_label (acfg, symbol);
3910
3911         for (i = 0; i < acfg->nmethods; ++i) {
3912                 if (acfg->cfgs [i])
3913                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
3914         }
3915
3916         sprintf (symbol, "ex_info_offsets");
3917         emit_section_change (acfg, ".text", 1);
3918         emit_global (acfg, symbol, FALSE);
3919         emit_alignment (acfg, 8);
3920         emit_label (acfg, symbol);
3921
3922         for (i = 0; i < acfg->nmethods; ++i) {
3923                 if (acfg->cfgs [i]) {
3924                         sprintf (symbol, ".Le_%x_p", i);
3925                         emit_symbol_diff (acfg, symbol, "ex", 0);
3926                 } else {
3927                         emit_int32 (acfg, 0);
3928                 }
3929         }
3930         emit_line (acfg);
3931 }
3932
3933 static void
3934 emit_unwind_info (MonoAotCompile *acfg)
3935 {
3936         int i;
3937         char symbol [128];
3938
3939         /* 
3940          * The unwind info contains a lot of duplicates so we emit each unique
3941          * entry once, and only store the offset from the start of the table in the
3942          * exception info.
3943          */
3944
3945         sprintf (symbol, "unwind_info");
3946         emit_section_change (acfg, ".text", 1);
3947         emit_alignment (acfg, 8);
3948         emit_label (acfg, symbol);
3949         emit_global (acfg, symbol, FALSE);
3950
3951         for (i = 0; i < acfg->unwind_ops->len; ++i) {
3952                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
3953                 guint8 *unwind_info;
3954                 guint32 unwind_info_len;
3955                 guint8 buf [16];
3956                 guint8 *p;
3957
3958                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
3959
3960                 p = buf;
3961                 encode_value (unwind_info_len, p, &p);
3962                 emit_bytes (acfg, buf, p - buf);
3963                 emit_bytes (acfg, unwind_info, unwind_info_len);
3964
3965                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
3966         }
3967 }
3968
3969 static void
3970 emit_class_info (MonoAotCompile *acfg)
3971 {
3972         int i;
3973         char symbol [256];
3974
3975         sprintf (symbol, "class_info");
3976         emit_section_change (acfg, ".text", 1);
3977         emit_global (acfg, symbol, FALSE);
3978         emit_alignment (acfg, 8);
3979         emit_label (acfg, symbol);
3980
3981         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
3982                 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
3983
3984         sprintf (symbol, "class_info_offsets");
3985         emit_section_change (acfg, ".text", 1);
3986         emit_global (acfg, symbol, FALSE);
3987         emit_alignment (acfg, 8);
3988         emit_label (acfg, symbol);
3989
3990         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3991                 sprintf (symbol, ".LK_I_%x", i);
3992                 emit_symbol_diff (acfg, symbol, "class_info", 0);
3993         }
3994         emit_line (acfg);
3995 }
3996
3997 typedef struct ClassNameTableEntry {
3998         guint32 token, index;
3999         struct ClassNameTableEntry *next;
4000 } ClassNameTableEntry;
4001
4002 static void
4003 emit_class_name_table (MonoAotCompile *acfg)
4004 {
4005         int i, table_size;
4006         guint32 token, hash;
4007         MonoClass *klass;
4008         GPtrArray *table;
4009         char *full_name;
4010         char symbol [256];
4011         ClassNameTableEntry *entry, *new_entry;
4012
4013         /*
4014          * Construct a chained hash table for mapping class names to typedef tokens.
4015          */
4016         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4017         table = g_ptr_array_sized_new (table_size);
4018         for (i = 0; i < table_size; ++i)
4019                 g_ptr_array_add (table, NULL);
4020         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4021                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4022                 klass = mono_class_get (acfg->image, token);
4023                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4024                 hash = mono_aot_str_hash (full_name) % table_size;
4025                 g_free (full_name);
4026
4027                 /* FIXME: Allocate from the mempool */
4028                 new_entry = g_new0 (ClassNameTableEntry, 1);
4029                 new_entry->token = token;
4030
4031                 entry = g_ptr_array_index (table, hash);
4032                 if (entry == NULL) {
4033                         new_entry->index = hash;
4034                         g_ptr_array_index (table, hash) = new_entry;
4035                 } else {
4036                         while (entry->next)
4037                                 entry = entry->next;
4038                         
4039                         entry->next = new_entry;
4040                         new_entry->index = table->len;
4041                         g_ptr_array_add (table, new_entry);
4042                 }
4043         }
4044
4045         /* Emit the table */
4046         sprintf (symbol, "class_name_table");
4047         emit_section_change (acfg, ".text", 0);
4048         emit_global (acfg, symbol, FALSE);
4049         emit_alignment (acfg, 8);
4050         emit_label (acfg, symbol);
4051
4052         /* FIXME: Optimize memory usage */
4053         g_assert (table_size < 65000);
4054         emit_int16 (acfg, table_size);
4055         g_assert (table->len < 65000);
4056         for (i = 0; i < table->len; ++i) {
4057                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4058
4059                 if (entry == NULL) {
4060                         emit_int16 (acfg, 0);
4061                         emit_int16 (acfg, 0);
4062                 } else {
4063                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
4064                         if (entry->next)
4065                                 emit_int16 (acfg, entry->next->index);
4066                         else
4067                                 emit_int16 (acfg, 0);
4068                 }
4069         }
4070 }
4071
4072 static void
4073 emit_image_table (MonoAotCompile *acfg)
4074 {
4075         int i;
4076         char symbol [256];
4077
4078         /*
4079          * The image table is small but referenced in a lot of places.
4080          * So we emit it at once, and reference its elements by an index.
4081          */
4082
4083         sprintf (symbol, "mono_image_table");
4084         emit_section_change (acfg, ".text", 1);
4085         emit_global (acfg, symbol, FALSE);
4086         emit_alignment (acfg, 8);
4087         emit_label (acfg, symbol);
4088
4089         emit_int32 (acfg, acfg->image_table->len);
4090         for (i = 0; i < acfg->image_table->len; i++) {
4091                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4092                 MonoAssemblyName *aname = &image->assembly->aname;
4093
4094                 /* FIXME: Support multi-module assemblies */
4095                 g_assert (image->assembly->image == image);
4096
4097                 emit_string (acfg, image->assembly_name);
4098                 emit_string (acfg, image->guid);
4099                 emit_string (acfg, aname->culture ? aname->culture : "");
4100                 emit_string (acfg, (const char*)aname->public_key_token);
4101
4102                 emit_alignment (acfg, 8);
4103                 emit_int32 (acfg, aname->flags);
4104                 emit_int32 (acfg, aname->major);
4105                 emit_int32 (acfg, aname->minor);
4106                 emit_int32 (acfg, aname->build);
4107                 emit_int32 (acfg, aname->revision);
4108         }
4109 }
4110
4111 static void
4112 emit_got_info (MonoAotCompile *acfg)
4113 {
4114         char symbol [256];
4115         int i, first_plt_got_patch, buf_size;
4116         guint8 *p, *buf;
4117         guint32 *got_info_offsets;
4118
4119         /* Add the patches needed by the PLT to the GOT */
4120         acfg->plt_got_offset_base = acfg->got_offset;
4121         first_plt_got_patch = acfg->got_patches->len;
4122         for (i = 1; i < acfg->plt_offset; ++i) {
4123                 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
4124
4125                 g_ptr_array_add (acfg->got_patches, patch_info);
4126         }
4127
4128         acfg->got_offset += acfg->plt_offset;
4129
4130         /**
4131          * FIXME: 
4132          * - optimize offsets table.
4133          * - reduce number of exported symbols.
4134          * - emit info for a klass only once.
4135          * - determine when a method uses a GOT slot which is guaranteed to be already 
4136          *   initialized.
4137          * - clean up and document the code.
4138          * - use String.Empty in class libs.
4139          */
4140
4141         /* Encode info required to decode shared GOT entries */
4142         buf_size = acfg->got_patches->len * 64;
4143         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4144         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
4145         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
4146         for (i = 0; i < acfg->got_patches->len; ++i) {
4147                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
4148
4149                 got_info_offsets [i] = p - buf;
4150                 if (i >= first_plt_got_patch)
4151                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
4152                 encode_value (ji->type, p, &p);
4153                 encode_patch (acfg, ji, p, &p);
4154         }
4155
4156         g_assert (p - buf <= buf_size);
4157
4158         acfg->stats.got_info_size = p - buf;
4159
4160         /* Emit got_info table */
4161         sprintf (symbol, "got_info");
4162         emit_section_change (acfg, ".text", 1);
4163         emit_global (acfg, symbol, FALSE);
4164         emit_alignment (acfg, 8);
4165         emit_label (acfg, symbol);
4166
4167         emit_bytes (acfg, buf, p - buf);
4168
4169         /* Emit got_info_offsets table */
4170         sprintf (symbol, "got_info_offsets");
4171         emit_section_change (acfg, ".text", 1);
4172         emit_global (acfg, symbol, FALSE);
4173         emit_alignment (acfg, 8);
4174         emit_label (acfg, symbol);
4175
4176         for (i = 0; i < acfg->got_patches->len; ++i)
4177                 emit_int32 (acfg, got_info_offsets [i]);
4178
4179         acfg->stats.got_info_offsets_size = acfg->got_patches->len * 4;
4180 }
4181
4182 static void
4183 emit_got (MonoAotCompile *acfg)
4184 {
4185         char symbol [256];
4186
4187         /* Don't make GOT global so accesses to it don't need relocations */
4188         sprintf (symbol, acfg->got_symbol);
4189         emit_section_change (acfg, ".bss", 0);
4190         emit_alignment (acfg, 8);
4191         emit_local_symbol (acfg, symbol, "got_end", FALSE);
4192         emit_label (acfg, symbol);
4193         if (acfg->got_offset > 0)
4194                 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4195
4196         sprintf (symbol, "got_end");
4197         emit_label (acfg, symbol);
4198
4199         sprintf (symbol, "mono_aot_got_addr");
4200         emit_section_change (acfg, ".data", 0);
4201         emit_global (acfg, symbol, FALSE);
4202         emit_alignment (acfg, 8);
4203         emit_label (acfg, symbol);
4204         emit_pointer (acfg, acfg->got_symbol);
4205 }
4206
4207 static void
4208 emit_globals (MonoAotCompile *acfg)
4209 {
4210         char *opts_str;
4211         char *build_info;
4212
4213         emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4214
4215         emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4216
4217         opts_str = g_strdup_printf ("%d", acfg->opts);
4218         emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4219         g_free (opts_str);
4220
4221         emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4222
4223         if (acfg->aot_opts.bind_to_runtime_version) {
4224                 build_info = mono_get_runtime_build_info ();
4225                 emit_string_symbol (acfg, "mono_runtime_version", build_info);
4226                 g_free (build_info);
4227         } else {
4228                 emit_string_symbol (acfg, "mono_runtime_version", "");
4229         }
4230
4231         /* 
4232          * When static linking, we emit a global which will point to the symbol table.
4233          */
4234         if (acfg->aot_opts.static_link) {
4235                 int i;
4236                 char symbol [256];
4237                 char *p;
4238
4239                 /* Emit a string holding the assembly name */
4240                 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4241
4242                 /* Emit the names */
4243                 for (i = 0; i < acfg->globals->len; ++i) {
4244                         char *name = g_ptr_array_index (acfg->globals, i);
4245
4246                         sprintf (symbol, "name_%d", i);
4247                         emit_section_change (acfg, ".text", 1);
4248                         emit_label (acfg, symbol);
4249                         emit_string (acfg, name);
4250                 }
4251
4252                 /* Emit the globals table */
4253                 sprintf (symbol, "globals");
4254                 emit_section_change (acfg, ".data", 0);
4255                 /* This is not a global, since it is accessed by the init function */
4256                 emit_alignment (acfg, 8);
4257                 emit_label (acfg, symbol);
4258
4259                 for (i = 0; i < acfg->globals->len; ++i) {
4260                         char *name = g_ptr_array_index (acfg->globals, i);
4261
4262                         sprintf (symbol, "name_%d", i);
4263                         emit_pointer (acfg, symbol);
4264
4265                         sprintf (symbol, "%s", name);
4266                         emit_pointer (acfg, symbol);
4267                 }
4268                 /* Null terminate the table */
4269                 emit_int32 (acfg, 0);
4270                 emit_int32 (acfg, 0);
4271
4272                 /* 
4273                  * Emit a global symbol which can be passed by an embedding app to
4274                  * mono_aot_register_module ().
4275                  */
4276 #if defined(__MACH__)
4277                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4278 #else
4279                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4280 #endif
4281
4282                 /* Get rid of characters which cannot occur in symbols */
4283                 p = symbol;
4284                 for (p = symbol; *p; ++p) {
4285                         if (!(isalnum (*p) || *p == '_'))
4286                                 *p = '_';
4287                 }
4288                 acfg->static_linking_symbol = g_strdup (symbol);
4289                 emit_global_inner (acfg, symbol, FALSE);
4290                 emit_alignment (acfg, 8);
4291                 emit_label (acfg, symbol);
4292                 emit_pointer (acfg, "globals");
4293         }
4294 }
4295
4296 static void
4297 emit_mem_end (MonoAotCompile *acfg)
4298 {
4299         char symbol [128];
4300
4301         sprintf (symbol, "mem_end");
4302         emit_section_change (acfg, ".text", 1);
4303         emit_global (acfg, symbol, FALSE);
4304         emit_alignment (acfg, 8);
4305         emit_label (acfg, symbol);
4306 }
4307
4308 /*
4309  * Emit a structure containing all the information not stored elsewhere.
4310  */
4311 static void
4312 emit_file_info (MonoAotCompile *acfg)
4313 {
4314         char symbol [128];
4315         int i;
4316
4317         sprintf (symbol, "mono_aot_file_info");
4318         emit_section_change (acfg, ".data", 0);
4319         emit_alignment (acfg, 8);
4320         emit_label (acfg, symbol);
4321         emit_global (acfg, symbol, FALSE);
4322
4323         /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
4324         emit_int32 (acfg, acfg->plt_got_offset_base);
4325         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4326         emit_int32 (acfg, acfg->plt_offset);
4327
4328         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4329                 emit_int32 (acfg, acfg->num_trampolines [i]);
4330         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4331                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
4332         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4333                 emit_int32 (acfg, acfg->trampoline_size [i]);
4334 }
4335
4336 static void
4337 emit_dwarf_info (MonoAotCompile *acfg)
4338 {
4339 #ifdef EMIT_DWARF_INFO
4340         int i;
4341         char symbol [128], symbol2 [128];
4342
4343         /* DIEs for methods */
4344         for (i = 0; i < acfg->nmethods; ++i) {
4345                 MonoCompile *cfg = acfg->cfgs [i];
4346
4347                 if (!cfg)
4348                         continue;
4349
4350                 sprintf (symbol, ".Lm_%x", i);
4351                 sprintf (symbol2, ".Lme_%x", i);
4352
4353                 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, NULL, 0, cfg->args, cfg->locals, cfg->unwind_ops, NULL);
4354         }
4355 #endif
4356 }
4357
4358 static void
4359 collect_methods (MonoAotCompile *acfg)
4360 {
4361         int i;
4362         MonoImage *image = acfg->image;
4363
4364         /* Collect methods */
4365         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4366                 MonoMethod *method;
4367                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4368
4369                 method = mono_get_method (acfg->image, token, NULL);
4370
4371                 if (!method) {
4372                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
4373                         exit (1);
4374                 }
4375                         
4376                 /* Load all methods eagerly to skip the slower lazy loading code */
4377                 mono_class_setup_methods (method->klass);
4378
4379                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4380                         /* Compile the wrapper instead */
4381                         /* We do this here instead of add_wrappers () because it is easy to do it here */
4382                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4383                         method = wrapper;
4384                 }
4385
4386                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4387                 add_method_with_index (acfg, method, i, FALSE);
4388                 acfg->method_index ++;
4389         }
4390
4391         add_generic_instances (acfg);
4392
4393         if (acfg->aot_opts.full_aot)
4394                 add_wrappers (acfg);
4395 }
4396
4397 static void
4398 compile_methods (MonoAotCompile *acfg)
4399 {
4400         int i, methods_len;
4401
4402         if (acfg->aot_opts.nthreads > 0) {
4403                 GPtrArray *frag;
4404                 int len, j;
4405                 GPtrArray *threads;
4406                 HANDLE handle;
4407                 gpointer *user_data;
4408                 MonoMethod **methods;
4409
4410                 methods_len = acfg->methods->len;
4411
4412                 len = acfg->methods->len / acfg->aot_opts.nthreads;
4413                 g_assert (len > 0);
4414                 /* 
4415                  * Partition the list of methods into fragments, and hand it to threads to
4416                  * process.
4417                  */
4418                 threads = g_ptr_array_new ();
4419                 /* Make a copy since acfg->methods is modified by compile_method () */
4420                 methods = g_new0 (MonoMethod*, methods_len);
4421                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
4422                 for (i = 0; i < methods_len; ++i)
4423                         methods [i] = g_ptr_array_index (acfg->methods, i);
4424                 i = 0;
4425                 while (i < methods_len) {
4426                         frag = g_ptr_array_new ();
4427                         for (j = 0; j < len; ++j) {
4428                                 if (i < methods_len) {
4429                                         g_ptr_array_add (frag, methods [i]);
4430                                         i ++;
4431                                 }
4432                         }
4433
4434                         user_data = g_new0 (gpointer, 3);
4435                         user_data [0] = mono_domain_get ();
4436                         user_data [1] = acfg;
4437                         user_data [2] = frag;
4438                         
4439                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
4440                         g_ptr_array_add (threads, handle);
4441                 }
4442                 g_free (methods);
4443
4444                 for (i = 0; i < threads->len; ++i) {
4445                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
4446                 }
4447         } else {
4448                 methods_len = 0;
4449         }
4450
4451         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
4452         for (i = methods_len; i < acfg->methods->len; ++i) {
4453                 /* This can new methods to acfg->methods */
4454                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4455         }
4456 }
4457
4458 static int
4459 compile_asm (MonoAotCompile *acfg)
4460 {
4461         char *command, *objfile;
4462         char *outfile_name, *tmp_outfile_name;
4463
4464 #if defined(TARGET_AMD64)
4465 #define AS_OPTIONS "--64"
4466 #elif defined(sparc) && SIZEOF_VOID_P == 8
4467 #define AS_OPTIONS "-xarch=v9"
4468 #else
4469 #define AS_OPTIONS ""
4470 #endif
4471
4472         if (acfg->aot_opts.asm_only) {
4473                 printf ("Output file: '%s'.\n", acfg->tmpfname);
4474                 if (acfg->aot_opts.static_link)
4475                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
4476                 return 0;
4477         }
4478
4479         if (acfg->aot_opts.static_link) {
4480                 if (acfg->aot_opts.outfile)
4481                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4482                 else
4483                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
4484         } else {
4485                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
4486         }
4487         command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
4488         printf ("Executing the native assembler: %s\n", command);
4489         if (system (command) != 0) {
4490                 g_free (command);
4491                 g_free (objfile);
4492                 return 1;
4493         }
4494
4495         g_free (command);
4496
4497         if (acfg->aot_opts.static_link) {
4498                 printf ("Output file: '%s'.\n", objfile);
4499                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
4500                 g_free (objfile);
4501                 return 0;
4502         }
4503
4504         if (acfg->aot_opts.outfile)
4505                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4506         else
4507                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4508
4509         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4510
4511 #if defined(sparc)
4512         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4513 #elif defined(__ppc__) && defined(__MACH__)
4514         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4515 #elif defined(PLATFORM_WIN32)
4516         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4517 #else
4518         command = g_strdup_printf ("ld -shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4519 #endif
4520         printf ("Executing the native linker: %s\n", command);
4521         if (system (command) != 0) {
4522                 g_free (tmp_outfile_name);
4523                 g_free (outfile_name);
4524                 g_free (command);
4525                 g_free (objfile);
4526                 return 1;
4527         }
4528
4529         g_free (command);
4530         unlink (objfile);
4531         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
4532         printf ("Stripping the binary: %s\n", com);
4533         system (com);
4534         g_free (com);*/
4535
4536 #if defined(TARGET_ARM) && !defined(__MACH__)
4537         /* 
4538          * gas generates 'mapping symbols' each time code and data is mixed, which 
4539          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
4540          */
4541         command = g_strdup_printf ("strip --strip-symbol=\\$a --strip-symbol=\\$d %s", tmp_outfile_name);
4542         printf ("Stripping the binary: %s\n", command);
4543         if (system (command) != 0) {
4544                 g_free (tmp_outfile_name);
4545                 g_free (outfile_name);
4546                 g_free (command);
4547                 g_free (objfile);
4548                 return 1;
4549         }
4550 #endif
4551
4552         rename (tmp_outfile_name, outfile_name);
4553
4554         g_free (tmp_outfile_name);
4555         g_free (outfile_name);
4556         g_free (objfile);
4557
4558         if (acfg->aot_opts.save_temps)
4559                 printf ("Retained input file.\n");
4560         else
4561                 unlink (acfg->tmpfname);
4562
4563         return 0;
4564 }
4565
4566 static MonoAotCompile*
4567 acfg_create (MonoAssembly *ass, guint32 opts)
4568 {
4569         MonoImage *image = ass->image;
4570         MonoAotCompile *acfg;
4571
4572         acfg = g_new0 (MonoAotCompile, 1);
4573         acfg->methods = g_ptr_array_new ();
4574         acfg->method_indexes = g_hash_table_new (NULL, NULL);
4575         acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4576         acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4577         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4578         acfg->got_patches = g_ptr_array_new ();
4579         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4580         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4581         acfg->image_hash = g_hash_table_new (NULL, NULL);
4582         acfg->image_table = g_ptr_array_new ();
4583         acfg->globals = g_ptr_array_new ();
4584         acfg->image = image;
4585         acfg->opts = opts;
4586         acfg->mempool = mono_mempool_new ();
4587         acfg->extra_methods = g_ptr_array_new ();
4588         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
4589         acfg->unwind_ops = g_ptr_array_new ();
4590         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
4591         InitializeCriticalSection (&acfg->mutex);
4592
4593         return acfg;
4594 }
4595
4596 static void
4597 acfg_free (MonoAotCompile *acfg)
4598 {
4599         int i;
4600
4601         img_writer_destroy (acfg->w);
4602         for (i = 0; i < acfg->nmethods; ++i)
4603                 if (acfg->cfgs [i])
4604                         g_free (acfg->cfgs [i]);
4605         g_free (acfg->cfgs);
4606         g_free (acfg->static_linking_symbol);
4607         g_ptr_array_free (acfg->methods, TRUE);
4608         g_ptr_array_free (acfg->got_patches, TRUE);
4609         g_ptr_array_free (acfg->image_table, TRUE);
4610         g_ptr_array_free (acfg->globals, TRUE);
4611         g_ptr_array_free (acfg->unwind_ops, TRUE);
4612         g_hash_table_destroy (acfg->method_indexes);
4613         g_hash_table_destroy (acfg->plt_offset_to_patch);
4614         g_hash_table_destroy (acfg->patch_to_plt_offset);
4615         g_hash_table_destroy (acfg->patch_to_got_offset);
4616         g_hash_table_destroy (acfg->method_to_cfg);
4617         g_hash_table_destroy (acfg->token_info_hash);
4618         g_hash_table_destroy (acfg->image_hash);
4619         g_hash_table_destroy (acfg->unwind_info_offsets);
4620         g_hash_table_destroy (acfg->method_label_hash);
4621         mono_mempool_destroy (acfg->mempool);
4622         g_free (acfg);
4623 }
4624
4625 int
4626 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4627 {
4628         MonoImage *image = ass->image;
4629         int res;
4630         MonoAotCompile *acfg;
4631         char *outfile_name, *tmp_outfile_name, *p;
4632         TV_DECLARE (atv);
4633         TV_DECLARE (btv);
4634
4635         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4636
4637         acfg = acfg_create (ass, opts);
4638
4639         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
4640         acfg->aot_opts.write_symbols = TRUE;
4641         acfg->aot_opts.ntrampolines = 10240;
4642
4643         mono_aot_parse_options (aot_options, &acfg->aot_opts);
4644
4645         //acfg->aot_opts.print_skipped_methods = TRUE;
4646
4647 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4648         if (acfg->aot_opts.full_aot) {
4649                 printf ("--aot=full is not supported on this platform.\n");
4650                 return 1;
4651         }
4652 #endif
4653
4654         if (acfg->aot_opts.static_link)
4655                 acfg->aot_opts.asm_writer = TRUE;
4656
4657         load_profile_files (acfg);
4658
4659         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
4660 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
4661         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? 1024 : 0;
4662 #endif
4663         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
4664
4665         acfg->got_symbol = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
4666
4667         /* Get rid of characters which cannot occur in symbols */
4668         p = acfg->got_symbol;
4669         for (p = acfg->got_symbol; *p; ++p) {
4670                 if (!(isalnum (*p) || *p == '_'))
4671                         *p = '_';
4672         }
4673
4674         acfg->method_index = 1;
4675
4676         collect_methods (acfg);
4677
4678         acfg->cfgs_size = acfg->methods->len + 32;
4679         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
4680
4681         /* PLT offset 0 is reserved for the PLT trampoline */
4682         acfg->plt_offset = 1;
4683
4684         /* GOT offset 0 is reserved for the address of the current assembly */
4685         {
4686                 MonoJumpInfo *ji;
4687
4688                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
4689                 ji->type = MONO_PATCH_INFO_IMAGE;
4690                 ji->data.image = acfg->image;
4691
4692                 get_got_offset (acfg, ji);
4693         }
4694
4695         TV_GETTIME (atv);
4696
4697         compile_methods (acfg);
4698
4699         TV_GETTIME (btv);
4700
4701         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
4702
4703         TV_GETTIME (atv);
4704
4705         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
4706                 if (acfg->aot_opts.outfile)
4707                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4708                 else
4709                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4710
4711                 /* 
4712                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
4713                  * it might be in another file system so the rename () won't work.
4714                  */
4715                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4716
4717                 acfg->fp = fopen (tmp_outfile_name, "w");
4718                 if (!acfg->fp) {
4719                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
4720                         return 1;
4721                 }
4722
4723                 acfg->w = img_writer_create (acfg->fp, TRUE);
4724                 acfg->use_bin_writer = TRUE;
4725         } else {
4726                 if (acfg->aot_opts.asm_only) {
4727                         if (acfg->aot_opts.outfile)
4728                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4729                         else
4730                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
4731                         acfg->fp = fopen (acfg->tmpfname, "w+");
4732                 } else {
4733                         int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
4734                         acfg->fp = fdopen (i, "w+");
4735                 }
4736                 g_assert (acfg->fp);
4737
4738                 acfg->w = img_writer_create (acfg->fp, FALSE);
4739                 
4740                 tmp_outfile_name = NULL;
4741                 outfile_name = NULL;
4742         }
4743
4744         if (!acfg->aot_opts.nodebug)
4745                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL);
4746
4747         img_writer_emit_start (acfg->w);
4748
4749         if (acfg->dwarf)
4750                 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
4751
4752         emit_code (acfg);
4753
4754         emit_info (acfg);
4755
4756         emit_extra_methods (acfg);
4757
4758         emit_method_order (acfg);
4759
4760         emit_trampolines (acfg);
4761
4762         emit_class_name_table (acfg);
4763
4764         emit_got_info (acfg);
4765
4766         emit_exception_info (acfg);
4767
4768         emit_unwind_info (acfg);
4769
4770         emit_class_info (acfg);
4771
4772         emit_plt (acfg);
4773
4774         emit_image_table (acfg);
4775
4776         emit_got (acfg);
4777
4778         emit_file_info (acfg);
4779
4780         emit_globals (acfg);
4781
4782         if (acfg->dwarf)
4783                 emit_dwarf_info (acfg);
4784
4785         emit_mem_end (acfg);
4786
4787         TV_GETTIME (btv);
4788
4789         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
4790
4791         printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT Info Offsets: %d GOT: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, acfg->stats.got_info_offsets_size, (int)(acfg->got_offset * sizeof (gpointer)));
4792
4793         TV_GETTIME (atv);
4794         res = img_writer_emit_writeout (acfg->w);
4795         if (res != 0) {
4796                 acfg_free (acfg);
4797                 return res;
4798         }
4799         if (acfg->use_bin_writer) {
4800                 int err = rename (tmp_outfile_name, outfile_name);
4801
4802                 if (err) {
4803                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
4804                         return 1;
4805                 }
4806         } else {
4807                 res = compile_asm (acfg);
4808                 if (res != 0) {
4809                         acfg_free (acfg);
4810                         return res;
4811                 }
4812         }
4813         TV_GETTIME (btv);
4814         acfg->stats.link_time = TV_ELAPSED (atv, btv);
4815
4816         printf ("Compiled %d out of %d methods (%d%%)\n", acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100);
4817         if (acfg->stats.genericcount)
4818                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4819         if (acfg->stats.abscount)
4820                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4821         if (acfg->stats.lmfcount)
4822                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4823         if (acfg->stats.ocount)
4824                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4825         printf ("Methods without GOT slots: %d (%d%%)\n", acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100);
4826         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4827
4828         /*
4829         printf ("GOT slot distribution:\n");
4830         for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4831                 if (acfg->stats.got_slot_types [i])
4832                         printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4833         */
4834
4835         printf ("JIT time: %d ms, Generation time: %d ms, Assembly+Link time: %d ms.\n", acfg->stats.jit_time / 1000, acfg->stats.gen_time / 1000, acfg->stats.link_time / 1000);
4836
4837         acfg_free (acfg);
4838         
4839         return 0;
4840 }
4841  
4842 /*
4843  * Support for emitting debug info for JITted code.
4844  *
4845  *   This works as follows:
4846  * - the runtime writes out an xdb.s file containing DWARF debug info.
4847  * - the user calls a gdb macro
4848  * - the macro compiles and loads this shared library using add-symbol-file.
4849  *
4850  * This is based on the xdebug functionality in the Kaffe Java VM.
4851  * 
4852  * We emit assembly code instead of using the ELF writer, so we can emit debug info
4853  * incrementally as each method is JITted, and the debugger doesn't have to call
4854  * into the runtime to emit the shared library, which would cause all kinds of
4855  * complications, like threading issues, and the fact that the ELF writer's
4856  * emit_writeout () function cannot be called more than once.
4857  */
4858
4859 /* The recommended gdb macro is: */
4860 /*
4861   define xdb
4862   shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
4863   add-symbol-file xdb.so 0
4864   end
4865 */
4866
4867 static MonoDwarfWriter *xdebug_writer;
4868 static FILE *xdebug_fp;
4869
4870 void
4871 mono_xdebug_init (void)
4872 {
4873         FILE *il_file;
4874         MonoImageWriter *w;
4875
4876         unlink ("xdb.s");
4877         xdebug_fp = fopen ("xdb.s", "w");
4878
4879         w = img_writer_create (xdebug_fp, FALSE);
4880
4881         img_writer_emit_start (w);
4882
4883         /* This file will contain the IL code for methods which don't have debug info */
4884         il_file = fopen ("xdb.il", "w");
4885
4886         xdebug_writer = mono_dwarf_writer_create (w, il_file);
4887
4888         /* Emit something so the file has a text segment */
4889         img_writer_emit_section_change (w, ".text", 0);
4890         img_writer_emit_string (w, "");
4891
4892         mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
4893 }
4894
4895 /*
4896  * mono_save_xdebug_info:
4897  *
4898  *   Emit debugging info for METHOD into an assembly file which can be assembled
4899  * and loaded into gdb to provide debugging info for JITted code.
4900  * LOCKING: Acquires the loader lock.
4901  */
4902 void
4903 mono_save_xdebug_info (MonoCompile *cfg)
4904 {
4905         if (!xdebug_writer)
4906                 return;
4907
4908         mono_loader_lock ();
4909         mono_dwarf_writer_emit_method (xdebug_writer, cfg, cfg->jit_info->method, NULL, NULL, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
4910         fflush (xdebug_fp);
4911         mono_loader_unlock ();
4912 }
4913
4914 /*
4915  * mono_save_trampoline_xdebug_info:
4916  *
4917  *   Same as mono_save_xdebug_info, but for trampolines.
4918  * LOCKING: Acquires the loader lock.
4919  */
4920 void
4921 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
4922 {
4923         if (!xdebug_writer)
4924                 return;
4925
4926         mono_loader_lock ();
4927         mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
4928         fflush (xdebug_fp);
4929         mono_loader_unlock ();
4930 }
4931
4932 #else
4933
4934 /* AOT disabled */
4935
4936 int
4937 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4938 {
4939         return 0;
4940 }
4941
4942 void
4943 mono_xdebug_init (void)
4944 {
4945 }
4946
4947 void
4948 mono_save_xdebug_info (MonoCompile *cfg)
4949 {
4950 }
4951
4952 void
4953 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
4954 {
4955 }
4956
4957 #endif