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