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