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