6bbba4789fbd48ae3cea8bf4bbaf71cd21b1fae1
[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 #include "config.h"
12 #include <sys/types.h>
13 #include <unistd.h>
14 #include <fcntl.h>
15 #include <string.h>
16 #ifndef PLATFORM_WIN32
17 #include <sys/mman.h>
18 #else
19 #include <winsock2.h>
20 #include <windows.h>
21 #endif
22
23 #include <errno.h>
24 #include <sys/stat.h>
25 #include <limits.h>    /* for PAGESIZE */
26 #ifndef PAGESIZE
27 #define PAGESIZE 4096
28 #endif
29
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/class.h>
32 #include <mono/metadata/object.h>
33 #include <mono/metadata/tokentype.h>
34 #include <mono/metadata/appdomain.h>
35 #include <mono/metadata/debug-helpers.h>
36 #include <mono/metadata/assembly.h>
37 #include <mono/metadata/metadata-internals.h>
38 #include <mono/metadata/marshal.h>
39 #include <mono/utils/mono-logger.h>
40 #include "mono/utils/mono-compiler.h"
41
42 #include "mini.h"
43
44 #ifndef DISABLE_AOT
45
46 #ifdef PLATFORM_WIN32
47 #define SHARED_EXT ".dll"
48 #elif defined(__ppc__) && defined(__MACH__)
49 #define SHARED_EXT ".dylib"
50 #else
51 #define SHARED_EXT ".so"
52 #endif
53
54 #if defined(sparc) || defined(__ppc__)
55 #define AS_STRING_DIRECTIVE ".asciz"
56 #else
57 /* GNU as */
58 #define AS_STRING_DIRECTIVE ".string"
59 #endif
60
61 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
62 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
63
64 typedef struct MonoAotOptions {
65         char *outfile;
66         gboolean save_temps;
67         gboolean write_symbols;
68         gboolean metadata_only;
69 } MonoAotOptions;
70
71 typedef struct MonoAotStats {
72         int ccount, mcount, lmfcount, abscount, wrappercount, gcount, ocount;
73         int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
74         int methods_without_got_slots, direct_calls, all_calls;
75         int got_slots;
76         int got_slot_types [MONO_PATCH_INFO_NONE];
77 } MonoAotStats;
78
79 /*#define USE_ELF_WRITER 1*/
80
81 #if defined(USE_ELF_WRITER)
82 #define USE_BIN_WRITER 1
83 #endif
84
85 #ifdef USE_BIN_WRITER
86
87 typedef struct _BinSymbol BinSymbol;
88 typedef struct _BinReloc BinReloc;
89 typedef struct _BinSection BinSection;
90
91 #else
92
93 /* emit mode */
94 enum {
95         EMIT_NONE,
96         EMIT_BYTE,
97         EMIT_LONG
98 };
99
100 #endif
101
102 typedef struct MonoAotCompile {
103         MonoImage *image;
104         MonoCompile **cfgs;
105         GHashTable *patch_to_plt_offset;
106         GHashTable *plt_offset_to_patch;
107         GHashTable *patch_to_shared_got_offset;
108         GPtrArray *shared_patches;
109         GHashTable *image_hash;
110         GHashTable *method_to_cfg;
111         GPtrArray *image_table;
112         GList *method_order;
113         guint32 got_offset, plt_offset;
114         guint32 *method_got_offsets;
115         gboolean *has_got_slots;
116         MonoAotOptions aot_opts;
117         guint32 nmethods;
118         guint32 opts;
119         MonoMemPool *mempool;
120         MonoAotStats stats;
121 #ifdef USE_BIN_WRITER
122         BinSymbol *symbols;
123         BinSection *sections;
124         BinSection *cur_section;
125         BinReloc *relocations;
126         GHashTable *labels;
127         int num_relocs;
128 #else
129         FILE *fp;
130         char *tmpfname;
131         int mode; /* emit mode */
132         int col_count; /* bytes emitted per .byte line */
133 #endif
134 } MonoAotCompile;
135
136 /* Keep in synch with MonoJumpInfoType */
137 static const char* patch_types [] = {
138         "bb",
139         "abs",
140         "label",
141         "method",
142         "method_jump",
143         "method_rel",
144         "methodconst",
145         "internal_method",
146         "switch",
147         "exc",
148         "exc_name",
149         "class",
150         "image",
151         "field",
152         "vtable",
153         "class_init",
154         "sflda",
155         "ldstr",
156         "ldtoken",
157         "type_from_handle",
158         "r4",
159         "r8",
160         "ip",
161         "iid",
162         "adjusted_iid",
163         "bb_ovf",
164         "exc_ovf",
165         "wrapper",
166         "got_offset",
167         "declsec",
168         "none"
169 };
170
171 static gboolean 
172 is_got_patch (MonoJumpInfoType patch_type)
173 {
174 #ifdef __x86_64__
175         return TRUE;
176 #elif defined(__i386__)
177         return TRUE;
178 #else
179         return FALSE;
180 #endif
181 }
182
183 #if defined(__ppc__) && defined(__MACH__)
184 static int
185 ilog2(register int value)
186 {
187         int count = -1;
188         while (value & ~0xf) count += 4, value >>= 4;
189         while (value) count++, value >>= 1;
190         return count;
191 }
192 #endif
193
194 #ifdef USE_BIN_WRITER
195
196 typedef struct _BinLabel BinLabel;
197 struct _BinLabel {
198         char *name;
199         BinSection *section;
200         int offset;
201 };
202
203 struct _BinReloc {
204         BinReloc *next;
205         char *val1;
206         char *val2;
207         BinSection *val2_section;
208         int val2_offset;
209         int offset;
210         BinSection *section;
211         int section_offset;
212 };
213
214 struct _BinSymbol {
215         BinSymbol *next;
216         char *name;
217         BinSection *section;
218         int offset;
219         gboolean is_function;
220         gboolean is_global;
221 };
222
223 struct _BinSection {
224         BinSection *next;
225         BinSection *parent;
226         char *name;
227         int subsection;
228         guint8 *data;
229         int data_len;
230         int cur_offset;
231         int file_offset;
232         int virt_offset;
233         int shidx;
234 };
235
236 static void
237 emit_start (MonoAotCompile *acfg)
238 {
239         acfg->labels = g_hash_table_new (g_str_hash, g_str_equal);
240 }
241
242 static void
243 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
244 {
245         BinSection *section;
246
247         if (acfg->cur_section && acfg->cur_section->subsection == subsection_index
248                         && strcmp (acfg->cur_section->name, section_name) == 0)
249                 return;
250         for (section = acfg->sections; section; section = section->next) {
251                 if (section->subsection == subsection_index && strcmp (section->name, section_name) == 0) {
252                         acfg->cur_section = section;
253                         return;
254                 }
255         }
256         if (!section) {
257                 section = g_new0 (BinSection, 1);
258                 section->name = g_strdup (section_name);
259                 section->subsection = subsection_index;
260                 section->next = acfg->sections;
261                 acfg->sections = section;
262                 acfg->cur_section = section;
263         }
264 }
265
266 static void
267 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
268 {
269         BinSymbol *symbol = g_new0 (BinSymbol, 1);
270         symbol->name = g_strdup (name);
271         symbol->is_function = func;
272         symbol->is_global = TRUE;
273         symbol->section = acfg->cur_section;
274         /* FIXME: we align after this call... */
275         symbol->offset = symbol->section->cur_offset;
276         symbol->next = acfg->symbols;
277         acfg->symbols = symbol;
278 }
279
280 static void
281 emit_label (MonoAotCompile *acfg, const char *name)
282 {
283         BinLabel *label = g_new0 (BinLabel, 1);
284         label->name = g_strdup (name);
285         label->section = acfg->cur_section;
286         label->offset = acfg->cur_section->cur_offset;
287         g_hash_table_insert (acfg->labels, label->name, label);
288 }
289
290 static void
291 emit_ensure_buffer (BinSection *section, int size)
292 {
293         int new_offset = section->cur_offset + size;
294         if (new_offset >= section->data_len) {
295                 int new_size = section->data_len? section->data_len * 2: 256;
296                 guint8 *data;
297                 while (new_size <= new_offset)
298                         new_size *= 2;
299                 data = g_malloc0 (new_size);
300                 memcpy (data, section->data, section->data_len);
301                 g_free (section->data);
302                 section->data = data;
303                 section->data_len = new_size;
304         }
305 }
306
307 static void
308 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
309 {
310         emit_ensure_buffer (acfg->cur_section, size);
311         memcpy (acfg->cur_section->data + acfg->cur_section->cur_offset, buf, size);
312         acfg->cur_section->cur_offset += size;
313 }
314
315 static void
316 emit_string (MonoAotCompile *acfg, const char *value)
317 {
318         int size = strlen (value) + 1;
319         emit_bytes (acfg, (const guint8*)value, size);
320 }
321
322 static void
323 emit_line (MonoAotCompile *acfg)
324 {
325         /* Nothing to do in binary writer */
326 }
327
328 static void
329 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
330 {
331         emit_section_change (acfg, ".text", 1);
332         emit_global (acfg, name, FALSE);
333         emit_label (acfg, name);
334         emit_string (acfg, value);
335 }
336
337 static void 
338 emit_alignment (MonoAotCompile *acfg, int size)
339 {
340         int offset = acfg->cur_section->cur_offset;
341         int add;
342         offset += (size - 1);
343         offset &= ~(size - 1);
344         add = offset - acfg->cur_section->cur_offset;
345         if (add) {
346                 emit_ensure_buffer (acfg->cur_section, add);
347                 acfg->cur_section->cur_offset += add;
348         }
349 }
350
351 static void
352 emit_pointer (MonoAotCompile *acfg, const char *target)
353 {
354         BinReloc *reloc;
355         emit_alignment (acfg, sizeof (gpointer));
356         reloc = g_new0 (BinReloc, 1);
357         reloc->val1 = g_strdup (target);
358         reloc->section = acfg->cur_section;
359         reloc->section_offset = acfg->cur_section->cur_offset;
360         reloc->next = acfg->relocations;
361         acfg->relocations = reloc;
362         if (strcmp (reloc->section->name, ".data") == 0) {
363                 acfg->num_relocs++;
364                 g_print ("reloc: %s at %d\n", target, acfg->cur_section->cur_offset);
365         }
366         acfg->cur_section->cur_offset += sizeof (gpointer);
367 }
368
369 static void
370 emit_int32 (MonoAotCompile *acfg, int value)
371 {
372         guint8 *data;
373         emit_ensure_buffer (acfg->cur_section, 4);
374         data = acfg->cur_section->data + acfg->cur_section->cur_offset;
375         acfg->cur_section->cur_offset += 4;
376         /* FIXME: little endian */
377         data [0] = value;
378         data [1] = value >> 8;
379         data [2] = value >> 16;
380         data [3] = value >> 24;
381 }
382
383 static void
384 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
385 {
386         BinReloc *reloc;
387         reloc = g_new0 (BinReloc, 1);
388         reloc->val1 = g_strdup (end);
389         if (strcmp (start, ".") == 0) {
390                 reloc->val2_section = acfg->cur_section;
391                 reloc->val2_offset = acfg->cur_section->cur_offset;
392         } else {
393                 reloc->val2 = g_strdup (start);
394         }
395         reloc->offset = offset;
396         reloc->section = acfg->cur_section;
397         reloc->section_offset = acfg->cur_section->cur_offset;
398         reloc->next = acfg->relocations;
399         acfg->relocations = reloc;
400         acfg->cur_section->cur_offset += 4;
401         /*if (strcmp (reloc->section->name, ".data") == 0) {
402                 acfg->num_relocs++;
403                 g_print ("reloc: %s - %s + %d at %d\n", end, start, offset, acfg->cur_section->cur_offset - 4);
404         }*/
405 }
406
407 static void
408 emit_zero_bytes (MonoAotCompile *acfg, int num)
409 {
410         emit_ensure_buffer (acfg->cur_section, num);
411         acfg->cur_section->cur_offset += num;
412 }
413
414 #ifdef USE_ELF_WRITER
415 enum {
416         SYM_LOCAL = 0 << 4,
417         SYM_GLOBAL = 1 << 4,
418         SYM_OBJECT = 1,
419         SYM_FUNC = 2,
420         SYM_SECTION = 3
421 };
422
423 enum {
424         SECT_NULL,
425         SECT_HASH,
426         SECT_DYNSYM,
427         SECT_DYNSTR,
428         SECT_REL_DYN,
429         SECT_TEXT,
430         SECT_DYNAMIC,
431         SECT_GOT_PLT,
432         SECT_DATA,
433         SECT_BSS,
434         SECT_SHSTRTAB,
435         SECT_SYMTAB,
436         SECT_STRTAB,
437         SECT_NUM
438 };
439
440 enum {
441         DYN_HASH = 4,
442         DYN_STRTAB = 5,
443         DYN_SYMTAB = 6,
444         DYN_STRSZ = 10,
445         DYN_SYMENT = 11,
446         DYN_REL = 17,
447         DYN_RELSZ = 18,
448         DYN_RELENT = 19,
449         DYN_RELCOUNT = 0x6ffffffa
450 };
451
452 static const char* section_names [] = {
453         "",
454         ".hash",
455         ".dynsym",
456         ".dynstr",
457         ".rel.dyn",
458         ".text",
459         ".dynamic",
460         ".got.plt",
461         ".data",
462         ".bss",
463         ".shstrtab",
464         ".symtab",
465         ".strtab"
466 };
467
468 static const guint8 section_type [] = {
469         0, 5, 11, 3, 9, 1,
470         6, 1, 1, 8, 3, 2, 3
471 };
472
473 static const guint8 section_link [] = {
474         0, 2, 3, 0, 2, 0, 3, 0, 0, 0, 0, 12, 0
475 };
476
477 static const guint8 section_esize [] = {
478         0, 4, 16, 0, 8, 0, 8, 4, 0, 0, 0, 16, 0
479 };
480
481 static const guint8 section_flags [] = {
482         0, 2, 2, 2, 2, 6, 3, 3, 3, 3, 0, 0, 0
483 };
484
485 static const guint16 section_align [] = {
486         0, 4, 4, 1, 4, 4096, 4, 4, 8, 8, 1, 4, 1
487 };
488
489 struct ElfHeader {
490         guint8  e_ident [16];
491         guint16 e_type;
492         guint16 e_machine;
493         guint32 e_version;
494         gsize   e_entry;
495         gsize   e_phoff;
496         gsize   e_shoff;
497         guint32 e_flags;
498         guint16 e_ehsize;
499         guint16 e_phentsize;
500         guint16 e_phnum;
501         guint16 e_shentsize;
502         guint16 e_shnum;
503         guint16 e_shstrndx;
504 };
505
506 struct ElfSectHeader {
507         guint32 sh_name;
508         guint32 sh_type;
509         gsize   sh_flags;
510         gsize   sh_addr;
511         gsize   sh_offset;
512         gsize   sh_size;
513         guint32 sh_link;
514         guint32 sh_info;
515         gsize   sh_addralign;
516         gsize   sh_entsize;
517 };
518
519 #if SIZEOF_VOID_P == 4
520
521 struct ElfProgHeader {
522         guint32 p_type;
523         guint32 p_offset;
524         guint32 p_vaddr;
525         guint32 p_paddr;
526         guint32 p_filesz;
527         guint32 p_memsz;
528         guint32 p_flags;
529         guint32 p_align;
530 };
531
532 typedef struct {
533         guint32 st_name;
534         guint32 st_value;
535         guint32 st_size;
536         guint8  st_info;
537         guint8  st_other;
538         guint16 st_shndx;
539 } ElfSymbol;
540
541 typedef struct {
542         guint32 addr;
543         guint32 value;
544 } ElfReloc;
545
546 typedef struct {
547         guint32 d_tag;
548         guint32 d_val;
549 } ElfDynamic;
550
551 #else
552
553 struct ElfProgHeader {
554         guint32 p_type;
555         guint32 p_flags;
556         guint64 p_offset;
557         guint64 p_vaddr;
558         guint64 p_paddr;
559         guint64 p_filesz;
560         guint64 p_memsz;
561         guint64 p_align;
562 };
563
564 typedef struct {
565         guint32 st_name;
566         guint8  st_info;
567         guint8  st_other;
568         guint16 st_shndx;
569         guint64 st_value;
570         guint64 st_size;
571 } ElfSymbol;
572
573 typedef struct {
574         guint64 addr;
575         guint64 value;
576 } ElfReloc;
577
578 typedef struct {
579         guint64 addr;
580         guint64 value;
581         guint64 addend;
582 } ElfRelocA;
583
584 typedef struct {
585         guint64 d_tag;
586         guint64 d_val;
587 } ElfDynamic;
588
589 #endif
590
591 typedef struct {
592         GString *data;
593         GHashTable *hash;
594 } ElfStrTable;
595
596 static int
597 str_table_add (ElfStrTable *table, const char* value)
598 {
599         int idx;
600         if (!table->data) {
601                 table->data = g_string_new_len ("", 1);
602                 table->hash = g_hash_table_new (g_str_hash, g_str_equal);
603         }
604         idx = GPOINTER_TO_UINT (g_hash_table_lookup (table->hash, value));
605         if (idx)
606                 return idx;
607         idx = table->data->len;
608         g_string_append (table->data, value);
609         g_string_append_c (table->data, 0);
610         g_hash_table_insert (table->hash, (void*)value, GUINT_TO_POINTER (idx));
611         return idx;
612 }
613
614 static void
615 append_subsection (MonoAotCompile *acfg, struct ElfSectHeader *sheaders, BinSection *sect, BinSection *add)
616 {
617         int offset = sect->cur_offset;
618         /*offset += (sheaders [sect->shidx].sh_addralign - 1);
619         offset &= ~(sheaders [sect->shidx].sh_addralign - 1);*/
620         offset += (8 - 1);
621         offset &= ~(8 - 1);
622         emit_ensure_buffer (sect, offset);
623         g_print ("section %s aligned to %d from %d\n", sect->name, offset, sect->cur_offset);
624         sect->cur_offset = offset;
625
626         emit_ensure_buffer (sect, add->cur_offset);
627         memcpy (sect->data + sect->cur_offset, add->data, add->cur_offset);
628         add->parent = sect;
629         sect->cur_offset += add->cur_offset;
630         add->cur_offset = offset; /* it becomes the offset in the parent section */
631         g_print ("subsection %d of %s added at offset %d (align: %d)\n", add->subsection, sect->name, add->cur_offset, sheaders [sect->shidx].sh_addralign);
632         add->data = NULL;
633         add->data_len = 0;
634 }
635
636 /* merge the subsections */
637 static int
638 collect_sections (MonoAotCompile *acfg, struct ElfSectHeader *sheaders, BinSection **out, int num)
639 {
640         int i, j, maxs, num_sections;
641         BinSection *sect;
642
643         num_sections = 0;
644         maxs = 0;
645         for (sect = acfg->sections; sect; sect = sect->next) {
646                 if (sect->subsection == 0) {
647                         out [num_sections++] = sect;
648                         g_assert (num_sections < num);
649                         if (strcmp (sect->name, ".text") == 0) {
650                                 sect->shidx = SECT_TEXT;
651                         } else if (strcmp (sect->name, ".data") == 0) {
652                                 sect->shidx = SECT_DATA;
653                         } else if (strcmp (sect->name, ".bss") == 0) {
654                                 sect->shidx = SECT_BSS;
655                         }
656                 }
657                 maxs = MAX (maxs, sect->subsection);
658         }
659         for (i = 0; i < num_sections; i++) {
660                 for (j = 1; j <= maxs; ++j) {
661                         for (sect = acfg->sections; sect; sect = sect->next) {
662                                 if (sect->subsection == j && strcmp (out [i]->name, sect->name) == 0) {
663                                         append_subsection (acfg, sheaders, out [i], sect);
664                                 }
665                         }
666                 }
667         }
668         return num_sections;
669 }
670
671 static unsigned long
672 elf_hash (const unsigned char *name)
673 {
674         unsigned long h = 0, g;
675         while (*name) {
676                 h = (h << 4) + *name++;
677                 if ((g = h & 0xf0000000))
678                         h ^= g >> 24;
679                 h &= ~g;
680         }
681         return h;
682 }
683
684 #define NUM_BUCKETS 17
685
686 static int*
687 build_hash (MonoAotCompile *acfg, int num_sections, ElfStrTable *dynstr)
688 {
689         int *data;
690         int num_symbols = 1 + num_sections + 3;
691         BinSymbol *symbol;
692
693         for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
694                 if (!symbol->is_global)
695                         continue;
696                 num_symbols++;
697                 str_table_add (dynstr, symbol->name);
698                 /*g_print ("adding sym: %s\n", symbol->name);*/
699         }
700         str_table_add (dynstr, "__bss_start");
701         str_table_add (dynstr, "_edata");
702         str_table_add (dynstr, "_end");
703
704         data = g_new0 (int, num_symbols + 2 + NUM_BUCKETS);
705         data [0] = NUM_BUCKETS;
706         data [1] = num_symbols;
707
708         return data;
709 }
710
711 static gsize
712 get_label_addr (MonoAotCompile *acfg, const char *name)
713 {
714         int offset;
715         BinLabel *lab;
716         BinSection *section;
717         gsize value;
718
719         lab = g_hash_table_lookup (acfg->labels, name);
720         section = lab->section;
721         offset = lab->offset;
722         if (section->parent) {
723                 value = section->parent->file_offset + section->cur_offset + offset;
724         } else {
725                 value = section->file_offset + offset;
726         }
727         return value;
728 }
729
730 static ElfSymbol*
731 collect_syms (MonoAotCompile *acfg, int *hash, ElfStrTable *strtab, struct ElfSectHeader *sheaders, int *num_syms)
732 {
733         ElfSymbol *symbols;
734         BinSymbol *symbol;
735         BinSection *section;
736         int i;
737         int *bucket;
738         int *chain;
739         unsigned long hashc;
740
741         if (hash)
742                 symbols = g_new0 (ElfSymbol, hash [1]);
743         else
744                 symbols = g_new0 (ElfSymbol, *num_syms + SECT_NUM + 10); /* FIXME */
745
746         /* the first symbol is undef, all zeroes */
747         i = 1;
748         if (sheaders) {
749                 int j;
750                 for (j = 1; j < SECT_NUM; ++j) {
751                         symbols [i].st_info = SYM_LOCAL | SYM_SECTION;
752                         symbols [i].st_shndx = j;
753                         symbols [i].st_value = sheaders [j].sh_addr;
754                         ++i;
755                 }
756         } else {
757                 for (section = acfg->sections; section; section = section->next) {
758                         if (section->parent)
759                                 continue;
760                         symbols [i].st_info = SYM_LOCAL | SYM_SECTION;
761                         if (strcmp (section->name, ".text") == 0) {
762                                 symbols [i].st_shndx = SECT_TEXT;
763                                 section->shidx = SECT_TEXT;
764                                 section->file_offset = 4096;
765                                 symbols [i].st_value = section->file_offset;
766                         } else if (strcmp (section->name, ".data") == 0) {
767                                 symbols [i].st_shndx = SECT_DATA;
768                                 section->shidx = SECT_DATA;
769                                 section->file_offset = 4096 + 28; /* FIXME */
770                                 symbols [i].st_value = section->file_offset;
771                         } else if (strcmp (section->name, ".bss") == 0) {
772                                 symbols [i].st_shndx = SECT_BSS;
773                                 section->shidx = SECT_BSS;
774                                 section->file_offset = 4096 + 28 + 8; /* FIXME */
775                                 symbols [i].st_value = section->file_offset;
776                         }
777                         ++i;
778                 }
779         }
780         for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
781                 int offset;
782                 BinLabel *lab;
783                 if (!symbol->is_global)
784                         continue;
785                 symbols [i].st_info = (symbol->is_function? SYM_FUNC : SYM_OBJECT) | SYM_GLOBAL;
786                 symbols [i].st_name = str_table_add (strtab, symbol->name);
787                 /*g_print ("sym name %s tabled to %d\n", symbol->name, symbols [i].st_name);*/
788                 section = symbol->section;
789                 symbols [i].st_shndx = section->parent? section->parent->shidx: section->shidx;
790                 lab = g_hash_table_lookup (acfg->labels, symbol->name);
791                 offset = lab->offset;
792                 if (section->parent) {
793                         symbols [i].st_value = section->parent->file_offset + section->cur_offset + offset;
794                 } else {
795                         symbols [i].st_value = section->file_offset + offset;
796                 }
797                 ++i;
798         }
799         /* add special symbols */
800         symbols [i].st_name = str_table_add (strtab, "__bss_start");
801         symbols [i].st_shndx = 0xfff1;
802         symbols [i].st_info = SYM_GLOBAL;
803         ++i;
804         symbols [i].st_name = str_table_add (strtab, "_edata");
805         symbols [i].st_shndx = 0xfff1;
806         symbols [i].st_info = SYM_GLOBAL;
807         ++i;
808         symbols [i].st_name = str_table_add (strtab, "_end");
809         symbols [i].st_shndx = 0xfff1;
810         symbols [i].st_info = SYM_GLOBAL;
811         ++i;
812
813         if (num_syms)
814                 *num_syms = i;
815
816         /* add to hash table */
817         if (hash) {
818                 bucket = hash + 2;
819                 chain = hash + 2 + hash [0];
820                 for (i = 0; i < hash [1]; ++i) {
821                         int slot;
822                         /*g_print ("checking %d '%s' (sym %d)\n", symbols [i].st_name, strtab->data->str + symbols [i].st_name, i);*/
823                         if (!symbols [i].st_name)
824                                 continue;
825                         hashc = elf_hash ((guint8*)strtab->data->str + symbols [i].st_name);
826                         slot = hashc % hash [0];
827                         /*g_print ("hashing '%s' at slot %d (sym %d)\n", strtab->data->str + symbols [i].st_name, slot, i);*/
828                         if (bucket [slot]) {
829                                 chain [i] = bucket [slot];
830                                 bucket [slot] = i;
831                         } else {
832                                 bucket [slot] = i;
833                         }
834                 }
835         }
836         return symbols;
837 }
838
839 static void
840 reloc_symbols (MonoAotCompile *acfg, ElfSymbol *symbols, struct ElfSectHeader *sheaders, ElfStrTable *strtab, gboolean dynamic)
841 {
842         BinSection *section;
843         BinSymbol *symbol;
844         int i;
845
846         i = 1;
847         if (dynamic) {
848                 for (section = acfg->sections; section; section = section->next) {
849                         if (section->parent)
850                                 continue;
851                         symbols [i].st_value = sheaders [section->shidx].sh_addr;
852                         ++i;
853                 }
854         } else {
855                 for (i = 1; i < SECT_NUM; ++i) {
856                         symbols [i].st_value = sheaders [i].sh_addr;
857                 }
858         }
859         for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
860                 int offset;
861                 BinLabel *lab;
862                 if (dynamic && !symbol->is_global)
863                         continue;
864                 section = symbol->section;
865                 lab = g_hash_table_lookup (acfg->labels, symbol->name);
866                 offset = lab->offset;
867                 if (section->parent) {
868                         symbols [i].st_value = sheaders [section->parent->shidx].sh_addr + section->cur_offset + offset;
869                 } else {
870                         symbols [i].st_value = sheaders [section->shidx].sh_addr + offset;
871                 }
872                 ++i;
873         }
874         /* __bss_start */
875         symbols [i].st_value = sheaders [SECT_BSS].sh_addr;
876         ++i;
877         /* _edata */
878         symbols [i].st_value = sheaders [SECT_DATA].sh_addr + sheaders [SECT_DATA].sh_size;
879         ++i;
880         /* _end */
881         symbols [i].st_value = sheaders [SECT_BSS].sh_addr + sheaders [SECT_BSS].sh_size;
882         ++i;
883 }
884
885 static ElfReloc*
886 resolve_relocations (MonoAotCompile *acfg)
887 {
888         BinReloc *reloc;
889         guint8 *data;
890         gsize end_val, start_val;
891         ElfReloc *rr;
892         int i;
893         gsize vaddr;
894
895         rr = g_new0 (ElfReloc, acfg->num_relocs);
896         i = 0;
897
898         for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
899                 end_val = get_label_addr (acfg, reloc->val1);
900                 if (reloc->val2) {
901                         start_val = get_label_addr (acfg, reloc->val2);
902                 } else if (reloc->val2_section) {
903                         start_val = reloc->val2_offset;
904                         if (reloc->val2_section->parent)
905                                 start_val += reloc->val2_section->parent->file_offset + reloc->val2_section->cur_offset;
906                         else
907                                 start_val += reloc->val2_section->file_offset;
908                 } else {
909                         start_val = 0;
910                 }
911                 end_val = end_val - start_val + reloc->offset;
912                 if (reloc->section->parent) {
913                         data = reloc->section->parent->data;
914                         data += reloc->section->cur_offset;
915                         data += reloc->section_offset;
916                         vaddr = reloc->section->parent->file_offset;
917                         vaddr += reloc->section->cur_offset;
918                         vaddr += reloc->section_offset;
919                 } else {
920                         data = reloc->section->data;
921                         data += reloc->section_offset;
922                         vaddr = reloc->section->file_offset;
923                         vaddr += reloc->section_offset;
924                 }
925                 /* FIXME: little endian */
926                 data [0] = end_val;
927                 data [1] = end_val >> 8;
928                 data [2] = end_val >> 16;
929                 data [3] = end_val >> 24;
930                 if (start_val == 0) {
931                         rr [i].addr = vaddr;
932                         rr [i].value = 8; /* FIXME: 386_RELATIVE */
933                         ++i;
934                         g_assert (i <= acfg->num_relocs);
935                 }
936         }
937         return rr;
938 }
939
940 static void
941 emit_writeout (MonoAotCompile *acfg)
942 {
943         char *outfile_name, *tmp_outfile_name;
944         FILE *file;
945         struct ElfHeader header;
946         struct ElfProgHeader progh [3];
947         struct ElfSectHeader secth [SECT_NUM];
948         ElfReloc *relocs;
949         ElfStrTable str_table = {NULL, NULL};
950         ElfStrTable sh_str_table = {NULL, NULL};
951         ElfStrTable dyn_str_table = {NULL, NULL};
952         BinSection* sections [6];
953         BinSection *text_section = NULL, *data_section = NULL, *bss_section = NULL;
954         ElfSymbol *dynsym;
955         ElfSymbol *symtab;
956         ElfDynamic dynamic [14];
957         int *hash;
958         int i, num_sections, file_offset, virt_offset, size, num_symtab;
959         int num_local_syms;
960
961         if (acfg->aot_opts.outfile)
962                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
963         else
964                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
965
966         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
967
968         unlink (tmp_outfile_name);
969         file = fopen (tmp_outfile_name, "w");
970         g_assert (file);
971
972         /* Section headers */
973         memset (&secth, 0, sizeof (secth));
974         memset (&dynamic, 0, sizeof (dynamic));
975         memset (&header, 0, sizeof (header));
976
977         for (i = 1; i < SECT_NUM; ++i) {
978                 secth [i].sh_name = str_table_add (&sh_str_table, section_names [i]);
979                 secth [i].sh_type = section_type [i];
980                 secth [i].sh_link = section_link [i];
981                 secth [i].sh_addralign = section_align [i];
982                 secth [i].sh_flags = section_flags [i];
983                 secth [i].sh_entsize = section_esize [i];
984         }
985         secth [SECT_DYNSYM].sh_info = 4;
986         secth [SECT_SYMTAB].sh_info = 20;
987
988         num_sections = collect_sections (acfg, secth, sections, 6);
989         hash = build_hash (acfg, num_sections, &dyn_str_table);
990         num_symtab = hash [1]; /* FIXME */
991         g_print ("num_sections: %d\n", num_sections);
992         g_print ("dynsym: %d, dynstr size: %d\n", hash [1], dyn_str_table.data->len);
993         for (i = 0; i < num_sections; ++i) {
994                 g_print ("section %s, size: %d, %x\n", sections [i]->name, sections [i]->cur_offset, sections [i]->cur_offset);
995         }
996
997         /* at this point we know where in the file the first segment sections go */
998         dynsym = collect_syms (acfg, hash, &dyn_str_table, NULL, NULL);
999         num_local_syms = hash [1];
1000         symtab = collect_syms (acfg, NULL, &str_table, secth, &num_local_syms);
1001
1002         for (i = 0; i < num_sections; ++i) {
1003                 if (sections [i]->shidx == SECT_TEXT) {
1004                         text_section = sections [i];
1005                 } else if (sections [i]->shidx == SECT_DATA) {
1006                         data_section = sections [i];
1007                 } else if (sections [i]->shidx == SECT_BSS) {
1008                         bss_section = sections [i];
1009                 }
1010         }
1011
1012         file_offset = virt_offset = sizeof (header) + sizeof (progh);
1013         secth [SECT_HASH].sh_addr = secth [SECT_HASH].sh_offset = file_offset;
1014         size = sizeof (int) * (2 + hash [0] + hash [1]);
1015         virt_offset = (file_offset += size);
1016         secth [SECT_HASH].sh_size = size;
1017         secth [SECT_DYNSYM].sh_addr = secth [SECT_DYNSYM].sh_offset = file_offset;
1018         size = sizeof (ElfSymbol) * hash [1];
1019         virt_offset = (file_offset += size);
1020         secth [SECT_DYNSYM].sh_size = size;
1021         secth [SECT_DYNSTR].sh_addr = secth [SECT_DYNSTR].sh_offset = file_offset;
1022         size = dyn_str_table.data->len;
1023         virt_offset = (file_offset += size);
1024         secth [SECT_DYNSTR].sh_size = size;
1025         file_offset += 4-1;
1026         file_offset &= ~(4-1);
1027         secth [SECT_REL_DYN].sh_addr = secth [SECT_REL_DYN].sh_offset = file_offset;
1028         size = sizeof (ElfReloc) * acfg->num_relocs;
1029         secth [SECT_REL_DYN].sh_size = size;
1030         virt_offset = (file_offset += size);
1031         secth [SECT_REL_DYN].sh_size = size;
1032         file_offset += 4096-1;
1033         file_offset &= ~(4096-1);
1034         virt_offset = file_offset;
1035         secth [SECT_TEXT].sh_addr = secth [SECT_TEXT].sh_offset = file_offset;
1036         size = text_section->cur_offset;
1037         secth [SECT_TEXT].sh_size = size;
1038         file_offset += size;
1039         file_offset += 4-1;
1040         file_offset &= ~(4-1);
1041         virt_offset = file_offset;
1042         /* .dynamic, .got.plt, .data, .bss here */
1043         secth [SECT_DYNAMIC].sh_addr = virt_offset;
1044         secth [SECT_DYNAMIC].sh_offset = file_offset;
1045         size = sizeof (dynamic);
1046         secth [SECT_DYNAMIC].sh_size = size;
1047         size += 4-1;
1048         size &= ~(4-1);
1049         file_offset += size;
1050         virt_offset += size;
1051         secth [SECT_GOT_PLT].sh_addr = virt_offset;
1052         secth [SECT_GOT_PLT].sh_offset = file_offset;
1053         size = 12;
1054         secth [SECT_GOT_PLT].sh_size = size;
1055         size += 8-1;
1056         size &= ~(8-1);
1057         file_offset += size;
1058         virt_offset += size;
1059         secth [SECT_DATA].sh_addr = virt_offset;
1060         secth [SECT_DATA].sh_offset = file_offset;
1061         size = data_section->cur_offset;
1062         secth [SECT_DATA].sh_size = size;
1063         size += 8-1;
1064         size &= ~(8-1);
1065         file_offset += size;
1066         virt_offset += size;
1067         secth [SECT_BSS].sh_addr = virt_offset;
1068         secth [SECT_BSS].sh_offset = file_offset;
1069         size = bss_section->cur_offset;
1070         secth [SECT_BSS].sh_size = size;
1071
1072         /* virtual doesn't matter anymore */
1073         secth [SECT_SHSTRTAB].sh_offset = file_offset;
1074         size = sh_str_table.data->len;
1075         secth [SECT_SHSTRTAB].sh_size = size;
1076         size += 4-1;
1077         size &= ~(4-1);
1078         file_offset += size;
1079         secth [SECT_SYMTAB].sh_offset = file_offset;
1080         size = sizeof (ElfSymbol) * num_local_syms;
1081         secth [SECT_SYMTAB].sh_size = size;
1082         file_offset += size;
1083         secth [SECT_STRTAB].sh_offset = file_offset;
1084         size = str_table.data->len;
1085         secth [SECT_STRTAB].sh_size = size;
1086         file_offset += size;
1087         file_offset += 4-1;
1088         file_offset &= ~(4-1);
1089
1090         text_section->file_offset = secth [SECT_TEXT].sh_offset;
1091         data_section->file_offset = secth [SECT_DATA].sh_offset;
1092         bss_section->file_offset = secth [SECT_BSS].sh_offset;
1093
1094         header.e_ident [0] = 0x7f; header.e_ident [1] = 'E';
1095         header.e_ident [2] = 'L'; header.e_ident [3] = 'F';
1096         header.e_ident [4] = SIZEOF_VOID_P == 4? 1: 2;
1097         header.e_ident [5] = 1; /* FIXME: little endian, bigendian is 2 */
1098         header.e_ident [6] = 1; /* version */
1099         header.e_ident [7] = 0; /* FIXME: */
1100         header.e_ident [8] = 0; /* FIXME: */
1101         for (i = 9; i < 16; ++i)
1102                 header.e_ident [i] = 0;
1103
1104         header.e_type = 3; /* shared library */
1105         header.e_machine = 3; /* FIXME: 386 */
1106         header.e_version = 1; /* FIXME:  */
1107
1108         header.e_phoff = sizeof (header);
1109         header.e_ehsize = sizeof (header);
1110         header.e_phentsize = sizeof (struct ElfProgHeader);
1111         header.e_phnum = 3;
1112         header.e_entry = secth [SECT_TEXT].sh_addr;
1113         header.e_shstrndx = 10;
1114         header.e_shentsize = sizeof (struct ElfSectHeader);
1115         header.e_shnum = SECT_NUM;
1116         header.e_shoff = file_offset;
1117
1118         /* dynamic data */
1119         i = 0;
1120         dynamic [i].d_tag = DYN_HASH;
1121         dynamic [i].d_val = secth [SECT_HASH].sh_offset;
1122         ++i;
1123         dynamic [i].d_tag = DYN_STRTAB;
1124         dynamic [i].d_val = secth [SECT_DYNSTR].sh_offset;
1125         ++i;
1126         dynamic [i].d_tag = DYN_SYMTAB;
1127         dynamic [i].d_val = secth [SECT_DYNSYM].sh_offset;
1128         ++i;
1129         dynamic [i].d_tag = DYN_STRSZ;
1130         dynamic [i].d_val = dyn_str_table.data->len;
1131         ++i;
1132         dynamic [i].d_tag = DYN_SYMENT;
1133         dynamic [i].d_val = sizeof (ElfSymbol);
1134         ++i;
1135         dynamic [i].d_tag = DYN_REL;
1136         dynamic [i].d_val = secth [SECT_REL_DYN].sh_offset;
1137         ++i;
1138         dynamic [i].d_tag = DYN_RELSZ;
1139         dynamic [i].d_val = secth [SECT_REL_DYN].sh_size;
1140         ++i;
1141         dynamic [i].d_tag = DYN_RELENT;
1142         dynamic [i].d_val = sizeof (ElfReloc);
1143         ++i;
1144         dynamic [i].d_tag = DYN_RELCOUNT;
1145         dynamic [i].d_val = acfg->num_relocs;
1146         ++i;
1147
1148         /* Program header */
1149         memset (&progh, 0, sizeof (progh));
1150         progh [0].p_type = 1; /* LOAD */
1151         progh [0].p_filesz = progh [0].p_memsz = secth [SECT_DYNAMIC].sh_offset;
1152         progh [0].p_align = 4096;
1153         progh [0].p_flags = 5;
1154
1155         progh [1].p_type = 1;
1156         progh [1].p_offset = secth [SECT_DYNAMIC].sh_offset;
1157         progh [1].p_vaddr = progh [1].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1158         progh [1].p_filesz = secth [SECT_BSS].sh_offset  - secth [SECT_DYNAMIC].sh_offset;
1159         progh [1].p_memsz = secth [SECT_BSS].sh_addr + secth [SECT_BSS].sh_size - secth [SECT_DYNAMIC].sh_addr;
1160         progh [1].p_align = 4096;
1161         progh [1].p_flags = 6;
1162
1163         progh [2].p_type = 2; /* DYNAMIC */
1164         progh [2].p_offset = secth [SECT_DYNAMIC].sh_offset;
1165         progh [2].p_vaddr = progh [2].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1166         progh [2].p_filesz = progh [2].p_memsz = secth [SECT_DYNAMIC].sh_size;
1167         progh [2].p_align = 4;
1168         progh [2].p_flags = 6;
1169
1170         reloc_symbols (acfg, dynsym, secth, &dyn_str_table, TRUE);
1171         reloc_symbols (acfg, symtab, secth, &str_table, FALSE);
1172         relocs = resolve_relocations (acfg);
1173
1174         fwrite (&header, sizeof (header), 1, file);
1175         fwrite (&progh, sizeof (progh), 1, file);
1176         fwrite (hash, sizeof (int) * (hash [0] + hash [1] + 2), 1, file);
1177         fwrite (dynsym, sizeof (ElfSymbol) * hash [1], 1, file);
1178         fwrite (dyn_str_table.data->str, dyn_str_table.data->len, 1, file);
1179         /* .rel.dyn */
1180         fseek (file, secth [SECT_REL_DYN].sh_offset, SEEK_SET);
1181         fwrite (relocs, sizeof (ElfReloc), acfg->num_relocs, file);
1182
1183         fseek (file, secth [SECT_TEXT].sh_offset, SEEK_SET);
1184         /* write .text, .data, .bss sections */
1185         fwrite (text_section->data, text_section->cur_offset, 1, file);
1186
1187         /* .dynamic */
1188         fwrite (dynamic, sizeof (dynamic), 1, file);
1189         /* .got.plt */
1190         size = secth [SECT_DYNAMIC].sh_addr;
1191         fwrite (&size, sizeof (size), 1, file);
1192         fseek (file, secth [SECT_DATA].sh_offset, SEEK_SET);
1193         fwrite (data_section->data, data_section->cur_offset, 1, file);
1194
1195         fseek (file, secth [SECT_SHSTRTAB].sh_offset, SEEK_SET);
1196         fwrite (sh_str_table.data->str, sh_str_table.data->len, 1, file);
1197         fseek (file, secth [SECT_SYMTAB].sh_offset, SEEK_SET);
1198         fwrite (symtab, sizeof (ElfSymbol) * num_local_syms, 1, file);
1199         fseek (file, secth [SECT_STRTAB].sh_offset, SEEK_SET);
1200         fwrite (str_table.data->str, str_table.data->len, 1, file);
1201         /*g_print ("file_offset %d vs %d\n", file_offset, ftell (file));*/
1202         /*g_assert (file_offset >= ftell (file));*/
1203         fseek (file, file_offset, SEEK_SET);
1204         fwrite (&secth, sizeof (secth), 1, file);
1205         fclose (file);
1206         rename (tmp_outfile_name, outfile_name);
1207
1208         g_free (tmp_outfile_name);
1209         g_free (outfile_name);
1210 }
1211
1212 #endif /* USE_ELF_WRITER */
1213
1214 #else
1215
1216 static void
1217 emit_start (MonoAotCompile *acfg)
1218 {
1219         int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
1220         acfg->fp = fdopen (i, "w+");
1221         g_assert (acfg->fp);
1222 }
1223
1224 static void
1225 emit_unset_mode (MonoAotCompile *acfg)
1226 {
1227         if (acfg->mode == EMIT_NONE)
1228                 return;
1229         fprintf (acfg->fp, "\n");
1230         acfg->mode = EMIT_NONE;
1231 }
1232
1233 static void
1234 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
1235 {
1236         emit_unset_mode (acfg);
1237 #if defined(PLATFORM_WIN32)
1238         fprintf (acfg->fp, ".section %s\n", section_name);
1239 #elif defined(sparc)
1240         /* For solaris as, GNU as should accept the same */
1241         fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1242 #elif defined(__ppc__) && defined(__MACH__)
1243         /* This needs to be made more precise on mach. */
1244         fprintf (acfg->fp, "%s\n", subsection_index == 0 ? ".text" : ".data");
1245 #else
1246         fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1247 #endif
1248 }
1249
1250 static void
1251 emit_symbol_type (MonoAotCompile *acfg, const char *name, gboolean func)
1252 {
1253         const char *stype;
1254
1255         if (func)
1256                 stype = "function";
1257         else
1258                 stype = "object";
1259
1260         emit_unset_mode (acfg);
1261 #if defined(sparc)
1262         fprintf (acfg->fp, "\t.type %s,#%s\n", name, stype);
1263 #elif defined(PLATFORM_WIN32)
1264
1265 #elif !(defined(__ppc__) && defined(__MACH__))
1266         fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1267 #elif defined(__x86_64__) || defined(__i386__)
1268         fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1269 #endif
1270 }
1271
1272 static void
1273 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
1274 {
1275         emit_unset_mode (acfg);
1276 #if  (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1277     // mach-o always uses a '_' prefix.
1278         fprintf (acfg->fp, "\t.globl _%s\n", name);
1279 #else
1280         fprintf (acfg->fp, "\t.globl %s\n", name);
1281 #endif
1282
1283         emit_symbol_type (acfg, name, func);
1284 }
1285
1286 static void
1287 emit_label (MonoAotCompile *acfg, const char *name)
1288 {
1289         emit_unset_mode (acfg);
1290 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1291     // mach-o always uses a '_' prefix.
1292         fprintf (acfg->fp, "_%s:\n", name);
1293 #else
1294         fprintf (acfg->fp, "%s:\n", name);
1295 #endif
1296
1297 #if defined(PLATFORM_WIN32)
1298         /* Emit a normal label too */
1299         fprintf (acfg->fp, "%s:\n", name);
1300 #endif
1301 }
1302
1303 static void
1304 emit_string (MonoAotCompile *acfg, const char *value)
1305 {
1306         emit_unset_mode (acfg);
1307         fprintf (acfg->fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
1308 }
1309
1310 static void
1311 emit_line (MonoAotCompile *acfg)
1312 {
1313         emit_unset_mode (acfg);
1314         fprintf (acfg->fp, "\n");
1315 }
1316
1317 static void
1318 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
1319 {
1320         emit_unset_mode (acfg);
1321         emit_section_change (acfg, ".text", 1);
1322         emit_global (acfg, name, FALSE);
1323         emit_label (acfg, name);
1324         emit_string (acfg, value);
1325 }
1326
1327 static void 
1328 emit_alignment (MonoAotCompile *acfg, int size)
1329 {
1330         emit_unset_mode (acfg);
1331 #if defined(__ppc__) && defined(__MACH__)
1332         // the mach-o assembler specifies alignments as powers of 2.
1333         fprintf (acfg->fp, "\t.align %d\t; ilog2\n", ilog2(size));
1334 #elif defined(__powerpc__)
1335         /* ignore on linux/ppc */
1336 #else
1337         fprintf (acfg->fp, "\t.align %d\n", size);
1338 #endif
1339 }
1340
1341 static void
1342 emit_pointer (MonoAotCompile *acfg, const char *target)
1343 {
1344         emit_unset_mode (acfg);
1345         emit_alignment (acfg, sizeof (gpointer));
1346 #if defined(__x86_64__)
1347         fprintf (acfg->fp, "\t.quad %s\n", target);
1348 #elif defined(sparc) && SIZEOF_VOID_P == 8
1349         fprintf (acfg->fp, "\t.xword %s\n", target);
1350 #else
1351         fprintf (acfg->fp, "\t.long %s\n", target);
1352 #endif
1353 }
1354
1355 static void
1356 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
1357 {
1358         int i;
1359         if (acfg->mode != EMIT_BYTE) {
1360                 acfg->mode = EMIT_BYTE;
1361                 acfg->col_count = 0;
1362         }
1363         for (i = 0; i < size; ++i, ++acfg->col_count) {
1364                 if ((acfg->col_count % 32) == 0)
1365                         fprintf (acfg->fp, "\n\t.byte ");
1366                 else
1367                         fprintf (acfg->fp, ", ");
1368                 fprintf (acfg->fp, "0x%x", buf [i]);
1369         }
1370 }
1371
1372 static void
1373 emit_int32 (MonoAotCompile *acfg, int value)
1374 {
1375         if (acfg->mode != EMIT_LONG) {
1376                 acfg->mode = EMIT_LONG;
1377                 acfg->col_count = 0;
1378         }
1379         if ((acfg->col_count++ % 8) == 0)
1380                 fprintf (acfg->fp, "\n\t.long ");
1381         else
1382                 fprintf (acfg->fp, ", ");
1383         fprintf (acfg->fp, "%d", value);
1384 }
1385
1386 static void
1387 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
1388 {
1389         if (acfg->mode != EMIT_LONG) {
1390                 acfg->mode = EMIT_LONG;
1391                 acfg->col_count = 0;
1392         }
1393         if ((acfg->col_count++ % 8) == 0)
1394                 fprintf (acfg->fp, "\n\t.long ");
1395         else
1396                 fprintf (acfg->fp, ", ");
1397         if (offset)
1398                 fprintf (acfg->fp, "%s - %s %c %d", end, start, offset < 0? ' ': '+', offset);
1399         else
1400                 fprintf (acfg->fp, "%s - %s", end, start);
1401 }
1402
1403 static void
1404 emit_zero_bytes (MonoAotCompile *acfg, int num)
1405 {
1406         emit_unset_mode (acfg);
1407         fprintf (acfg->fp, "\t.skip %d\n", num);
1408 }
1409
1410 static void
1411 emit_writeout (MonoAotCompile *acfg)
1412 {
1413         char *command, *objfile;
1414         char *outfile_name, *tmp_outfile_name;
1415
1416         fclose (acfg->fp);
1417
1418 #if defined(__x86_64__)
1419 #define AS_OPTIONS "--64"
1420 #elif defined(sparc) && SIZEOF_VOID_P == 8
1421 #define AS_OPTIONS "-xarch=v9"
1422 #else
1423 #define AS_OPTIONS ""
1424 #endif
1425         command = g_strdup_printf ("as %s %s -o %s.o", AS_OPTIONS, acfg->tmpfname, acfg->tmpfname);
1426         printf ("Executing the native assembler: %s\n", command);
1427         if (system (command) != 0) {
1428                 g_free (command);
1429                 return;
1430         }
1431
1432         g_free (command);
1433
1434         if (acfg->aot_opts.outfile)
1435                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1436         else
1437                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1438
1439         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1440
1441 #if defined(sparc)
1442         command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
1443 #elif defined(__ppc__) && defined(__MACH__)
1444         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
1445 #elif defined(PLATFORM_WIN32)
1446         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
1447 #else
1448         command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1449 #endif
1450         printf ("Executing the native linker: %s\n", command);
1451         if (system (command) != 0) {
1452                 g_free (tmp_outfile_name);
1453                 g_free (outfile_name);
1454                 g_free (command);
1455                 return;
1456         }
1457
1458         g_free (command);
1459         objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
1460         unlink (objfile);
1461         g_free (objfile);
1462         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
1463         printf ("Stripping the binary: %s\n", com);
1464         system (com);
1465         g_free (com);*/
1466
1467         rename (tmp_outfile_name, outfile_name);
1468
1469         g_free (tmp_outfile_name);
1470         g_free (outfile_name);
1471
1472         if (acfg->aot_opts.save_temps)
1473                 printf ("Retained input file.\n");
1474         else
1475                 unlink (acfg->tmpfname);
1476
1477 }
1478
1479 #endif /* ASM_WRITER */
1480
1481 static void
1482 emit_byte (MonoAotCompile *acfg, guint8 val)
1483 {
1484         emit_bytes (acfg, &val, 1);
1485 }
1486
1487 static guint32
1488 mono_get_field_token (MonoClassField *field) 
1489 {
1490         MonoClass *klass = field->parent;
1491         int i;
1492
1493         for (i = 0; i < klass->field.count; ++i) {
1494                 if (field == &klass->fields [i])
1495                         return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1496         }
1497
1498         g_assert_not_reached ();
1499         return 0;
1500 }
1501
1502 static inline void
1503 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1504 {
1505         guint8 *p = buf;
1506
1507         //printf ("ENCODE: %d 0x%x.\n", value, value);
1508
1509         /* 
1510          * Same encoding as the one used in the metadata, extended to handle values
1511          * greater than 0x1fffffff.
1512          */
1513         if ((value >= 0) && (value <= 127))
1514                 *p++ = value;
1515         else if ((value >= 0) && (value <= 16383)) {
1516                 p [0] = 0x80 | (value >> 8);
1517                 p [1] = value & 0xff;
1518                 p += 2;
1519         } else if ((value >= 0) && (value <= 0x1fffffff)) {
1520                 p [0] = (value >> 24) | 0xc0;
1521                 p [1] = (value >> 16) & 0xff;
1522                 p [2] = (value >> 8) & 0xff;
1523                 p [3] = value & 0xff;
1524                 p += 4;
1525         }
1526         else {
1527                 p [0] = 0xff;
1528                 p [1] = (value >> 24) & 0xff;
1529                 p [2] = (value >> 16) & 0xff;
1530                 p [3] = (value >> 8) & 0xff;
1531                 p [4] = value & 0xff;
1532                 p += 5;
1533         }
1534         if (endbuf)
1535                 *endbuf = p;
1536 }
1537
1538 static guint32
1539 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1540 {
1541         guint32 index;
1542
1543         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1544         if (index)
1545                 return index - 1;
1546         else {
1547                 index = g_hash_table_size (cfg->image_hash);
1548                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1549                 g_ptr_array_add (cfg->image_table, image);
1550                 return index;
1551         }
1552 }
1553
1554 static void
1555 encode_klass_info (MonoAotCompile *cfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1556 {
1557         if (!klass->type_token) {
1558                 /* Array class */
1559                 g_assert (klass->rank > 0);
1560                 g_assert (klass->element_class->type_token);
1561                 encode_value (MONO_TOKEN_TYPE_DEF, buf, &buf);
1562                 encode_value (get_image_index (cfg, klass->image), buf, &buf);
1563                 g_assert (mono_metadata_token_code (klass->element_class->type_token) == MONO_TOKEN_TYPE_DEF);
1564                 encode_value (klass->element_class->type_token - MONO_TOKEN_TYPE_DEF, buf, &buf);
1565                 encode_value (klass->rank, buf, &buf);
1566         }
1567         else {
1568                 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1569                 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, buf, &buf);
1570                 encode_value (get_image_index (cfg, klass->image), buf, &buf);
1571         }
1572         *endbuf = buf;
1573 }
1574
1575 static void
1576 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1577 {
1578         guint32 token = mono_get_field_token (field);
1579
1580         encode_klass_info (cfg, field->parent, buf, &buf);
1581         g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1582         encode_value (token - MONO_TOKEN_FIELD_DEF, buf, &buf);
1583         *endbuf = buf;
1584 }
1585
1586 static void
1587 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1588 {
1589         guint32 image_index = get_image_index (acfg, method->klass->image);
1590         guint32 token = method->token;
1591         g_assert (image_index < 256);
1592         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1593
1594         encode_value ((image_index << 24) + (mono_metadata_token_index (token)), buf, &buf);
1595         *endbuf = buf;
1596 }
1597
1598 static gint
1599 compare_patches (gconstpointer a, gconstpointer b)
1600 {
1601         int i, j;
1602
1603         i = (*(MonoJumpInfo**)a)->ip.i;
1604         j = (*(MonoJumpInfo**)b)->ip.i;
1605
1606         if (i < j)
1607                 return -1;
1608         else
1609                 if (i > j)
1610                         return 1;
1611         else
1612                 return 0;
1613 }
1614
1615 static int
1616 get_plt_index (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1617 {
1618         int res = -1;
1619         int idx;
1620
1621         switch (patch_info->type) {
1622         case MONO_PATCH_INFO_METHOD:
1623         case MONO_PATCH_INFO_WRAPPER:
1624         case MONO_PATCH_INFO_INTERNAL_METHOD:
1625         case MONO_PATCH_INFO_CLASS_INIT: {
1626                 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1627                 gpointer patch_id = NULL;
1628
1629                 /* First check for an existing patch */
1630                 switch (patch_info->type) {
1631                 case MONO_PATCH_INFO_METHOD:
1632                         patch_id = patch_info->data.method;
1633                         break;
1634                 case MONO_PATCH_INFO_INTERNAL_METHOD:
1635                         patch_id = (gpointer)patch_info->data.name;
1636                         break;
1637                 case MONO_PATCH_INFO_CLASS_INIT:
1638                         patch_id = patch_info->data.klass;
1639                         break;
1640                 case MONO_PATCH_INFO_WRAPPER:
1641                         /* A bit ugly, but works */
1642                         g_assert (patch_info->data.method->wrapper_type < sizeof (MonoMethod));
1643                         patch_id = (gpointer)(((guint8*)patch_info->data.method) + patch_info->data.method->wrapper_type);
1644                         break;
1645                 default:
1646                         g_assert_not_reached ();
1647                 }
1648
1649                 if (patch_id) {
1650                         idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_id));
1651                         if (idx)
1652                                 res = idx;
1653                         else
1654                                 g_hash_table_insert (acfg->patch_to_plt_offset, patch_id, GUINT_TO_POINTER (acfg->plt_offset));
1655                 }
1656
1657                 if (res == -1) {
1658                         res = acfg->plt_offset;
1659                         g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (acfg->plt_offset), new_ji);
1660                         acfg->plt_offset ++;
1661                 }
1662
1663                 /* Nullify the patch */
1664                 patch_info->type = MONO_PATCH_INFO_NONE;
1665
1666                 return res;
1667         }
1668         default:
1669                 return -1;
1670         }
1671 }
1672
1673 /**
1674  * get_got_offset:
1675  *
1676  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
1677  * JI could be found if it exists, otherwise allocates a new one.
1678  */
1679 static guint32
1680 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1681 {
1682         guint32 got_offset;
1683
1684         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
1685         if (got_offset)
1686                 return got_offset - 1;
1687
1688         got_offset = acfg->got_offset;
1689         acfg->got_offset ++;
1690
1691         acfg->stats.got_slots ++;
1692         acfg->stats.got_slot_types [ji->type] ++;
1693
1694         return got_offset;
1695 }
1696
1697 static guint32
1698 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1699 {
1700         MonoJumpInfo *copy;
1701         guint32 got_offset;
1702
1703         if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
1704                 got_offset = get_got_offset (acfg, ji);
1705                 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
1706                 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
1707                 g_ptr_array_add (acfg->shared_patches, copy);
1708         }
1709
1710         return get_got_offset (acfg, ji);
1711 }
1712
1713 static void
1714 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
1715 {
1716         MonoMethod *method;
1717         int i, pindex, method_index;
1718         guint8 *code;
1719         char *symbol;
1720         int func_alignment = 16;
1721         GPtrArray *patches;
1722         MonoJumpInfo *patch_info;
1723         MonoMethodHeader *header;
1724         gboolean skip;
1725         guint32 got_slot;
1726
1727         method = cfg->method;
1728         code = cfg->native_code;
1729         header = mono_method_get_header (method);
1730
1731         method_index = mono_metadata_token_index (method->token);
1732
1733         /* Make the labels local */
1734         symbol = g_strdup_printf (".Lm_%x", method_index);
1735
1736         emit_alignment (acfg, func_alignment);
1737         emit_label (acfg, symbol);
1738         if (acfg->aot_opts.write_symbols)
1739                 emit_global (acfg, symbol, TRUE);
1740
1741         if (cfg->verbose_level > 0)
1742                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
1743
1744         acfg->stats.code_size += cfg->code_len;
1745
1746         /* Collect and sort relocations */
1747         patches = g_ptr_array_new ();
1748         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
1749                 g_ptr_array_add (patches, patch_info);
1750         g_ptr_array_sort (patches, compare_patches);
1751
1752         acfg->method_got_offsets [method_index] = acfg->got_offset;
1753         for (i = 0; i < cfg->code_len; i++) {
1754                 patch_info = NULL;
1755                 for (pindex = 0; pindex < patches->len; ++pindex) {
1756                         patch_info = g_ptr_array_index (patches, pindex);
1757                         if (patch_info->ip.i == i)
1758                                 break;
1759                 }
1760
1761 #ifdef MONO_ARCH_HAVE_PIC_AOT
1762
1763                 skip = FALSE;
1764                 if (patch_info && (pindex < patches->len)) {
1765                         switch (patch_info->type) {
1766                         case MONO_PATCH_INFO_LABEL:
1767                         case MONO_PATCH_INFO_BB:
1768                         case MONO_PATCH_INFO_NONE:
1769                                 break;
1770                         case MONO_PATCH_INFO_GOT_OFFSET: {
1771                                 guint32 offset = mono_arch_get_patch_offset (code + i);
1772                                 emit_bytes (acfg, code + i, offset);
1773                                 emit_symbol_diff (acfg, "got", ".", offset);
1774
1775                                 i += offset + 4 - 1;
1776                                 skip = TRUE;
1777                                 break;
1778                         }
1779                         default: {
1780                                 int plt_index;
1781                                 char *direct_call_target;
1782
1783                                 if (!is_got_patch (patch_info->type))
1784                                         break;
1785
1786                                 /*
1787                                  * If this patch is a call, try emitting a direct call instead of
1788                                  * through a PLT entry. This is possible if the called method is in
1789                                  * the same assembly and requires no initialization.
1790                                  */
1791                                 direct_call_target = NULL;
1792                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == cfg->method->klass->image)) {
1793                                         MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
1794                                         if (callee_cfg) {
1795                                                 guint32 callee_idx = mono_metadata_token_index (callee_cfg->method->token);
1796                                                 if (!acfg->has_got_slots [callee_idx] && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)) {
1797                                                         //printf ("DIRECT: %s %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (callee_cfg->method, TRUE));
1798                                                         direct_call_target = g_strdup_printf (".Lm_%x", mono_metadata_token_index (callee_cfg->method->token));
1799                                                         patch_info->type = MONO_PATCH_INFO_NONE;
1800                                                         acfg->stats.direct_calls ++;
1801                                                 }
1802                                         }
1803
1804                                         acfg->stats.all_calls ++;
1805                                 }
1806
1807                                 if (!direct_call_target) {
1808                                         plt_index = get_plt_index (acfg, patch_info);
1809                                         if (plt_index != -1) {
1810                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
1811                                                 direct_call_target = g_strdup_printf (".Lp_%d", plt_index);
1812                                         }
1813                                 }
1814
1815                                 if (direct_call_target) {
1816 #if defined(__i386__) || defined(__x86_64__)
1817                                         g_assert (code [i] == 0xe8);
1818                                         /* Need to make sure this is exactly 5 bytes long */
1819                                         emit_byte (acfg, '\xe8');
1820                                         emit_symbol_diff (acfg, direct_call_target, ".", -4);
1821                                         i += 4;
1822 #else
1823                                         g_assert_not_reached ();
1824 #endif
1825                                 } else {
1826                                         got_slot = get_got_offset (acfg, patch_info);
1827
1828                                         emit_bytes (acfg, code + i, mono_arch_get_patch_offset (code + i));
1829 #ifdef __x86_64__
1830                                         emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1831 #elif defined(__i386__)
1832                                         emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1833 #endif
1834                                         
1835                                         i += mono_arch_get_patch_offset (code + i) + 4 - 1;
1836                                 }
1837                                 skip = TRUE;
1838                         }
1839                         }
1840                 }
1841 #endif /* MONO_ARCH_HAVE_PIC_AOT */
1842
1843                 if (!skip)
1844                         emit_bytes (acfg, code + i, 1);
1845         }
1846         emit_line (acfg);
1847 }
1848
1849 /**
1850  * encode_patch:
1851  *
1852  *  Encode PATCH_INFO into its disk representation. If SHARED is true, encode some types
1853  * of patches by allocating a GOT entry for them, and encode the GOT offset instead.
1854  */
1855 static void
1856 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf, gboolean shared)
1857 {
1858         guint8 *p = buf;
1859
1860         switch (patch_info->type) {
1861         case MONO_PATCH_INFO_NONE:
1862                 break;
1863         case MONO_PATCH_INFO_IMAGE:
1864                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
1865                 break;
1866         case MONO_PATCH_INFO_METHOD_REL:
1867                 encode_value ((gint)patch_info->data.offset, p, &p);
1868                 break;
1869         case MONO_PATCH_INFO_SWITCH: {
1870                 gpointer *table = (gpointer *)patch_info->data.table->table;
1871                 int k;
1872
1873                 encode_value (patch_info->data.table->table_size, p, &p);
1874                 for (k = 0; k < patch_info->data.table->table_size; k++)
1875                         encode_value ((int)(gssize)table [k], p, &p);
1876                 break;
1877         }
1878         case MONO_PATCH_INFO_METHODCONST:
1879         case MONO_PATCH_INFO_METHOD:
1880         case MONO_PATCH_INFO_METHOD_JUMP:
1881                 encode_method_ref (acfg, patch_info->data.method, p, &p);
1882                 break;
1883         case MONO_PATCH_INFO_INTERNAL_METHOD: {
1884                 guint32 len = strlen (patch_info->data.name);
1885
1886                 encode_value (len, p, &p);
1887
1888                 memcpy (p, patch_info->data.name, len);
1889                 p += len;
1890                 *p++ = '\0';
1891                 break;
1892         }
1893         case MONO_PATCH_INFO_LDSTR: {
1894                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
1895                 guint32 token = patch_info->data.token->token;
1896                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
1897                 /* 
1898                  * An optimization would be to emit shared code for ldstr 
1899                  * statements followed by a throw.
1900                  */
1901                 encode_value (image_index, p, &p);
1902                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
1903                 break;
1904         }
1905         case MONO_PATCH_INFO_DECLSEC:
1906         case MONO_PATCH_INFO_LDTOKEN:
1907         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1908                 if (shared) {
1909                         guint32 offset = get_got_offset (acfg, patch_info);
1910                         encode_value (offset, p, &p);
1911                 } else {
1912                         encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
1913                         encode_value (patch_info->data.token->token, p, &p);
1914                 }
1915                 break;
1916         case MONO_PATCH_INFO_EXC_NAME: {
1917                 MonoClass *ex_class;
1918
1919                 ex_class =
1920                         mono_class_from_name (mono_defaults.exception_class->image,
1921                                                                   "System", patch_info->data.target);
1922                 g_assert (ex_class);
1923                 encode_klass_info (acfg, ex_class, p, &p);
1924                 break;
1925         }
1926         case MONO_PATCH_INFO_R4:
1927                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
1928                 break;
1929         case MONO_PATCH_INFO_R8:
1930                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
1931                 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
1932                 break;
1933         case MONO_PATCH_INFO_VTABLE:
1934         case MONO_PATCH_INFO_CLASS:
1935         case MONO_PATCH_INFO_IID:
1936         case MONO_PATCH_INFO_ADJUSTED_IID:
1937                 if (shared) {
1938                         guint32 offset = get_got_offset (acfg, patch_info);
1939                         encode_value (offset, p, &p);
1940                 } else {
1941                         encode_klass_info (acfg, patch_info->data.klass, p, &p);
1942                 }
1943                 break;
1944         case MONO_PATCH_INFO_CLASS_INIT:
1945                 encode_klass_info (acfg, patch_info->data.klass, p, &p);
1946                 break;
1947         case MONO_PATCH_INFO_FIELD:
1948         case MONO_PATCH_INFO_SFLDA:
1949                 if (shared) {
1950                         guint32 offset = get_got_offset (acfg, patch_info);
1951                         encode_value (offset, p, &p);
1952                 } else {
1953                         encode_field_info (acfg, patch_info->data.field, p, &p);
1954                 }
1955                 break;
1956         case MONO_PATCH_INFO_WRAPPER: {
1957                 encode_value (patch_info->data.method->wrapper_type, p, &p);
1958
1959                 switch (patch_info->data.method->wrapper_type) {
1960                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
1961                         MonoMethod *m;
1962                         guint32 image_index;
1963                         guint32 token;
1964
1965                         m = mono_marshal_method_from_wrapper (patch_info->data.method);
1966                         image_index = get_image_index (acfg, m->klass->image);
1967                         token = m->token;
1968                         g_assert (image_index < 256);
1969                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1970
1971                         encode_value ((image_index << 24) + (mono_metadata_token_index (token)), p, &p);
1972                         break;
1973                 }
1974                 case MONO_WRAPPER_PROXY_ISINST:
1975                 case MONO_WRAPPER_LDFLD:
1976                 case MONO_WRAPPER_LDFLDA:
1977                 case MONO_WRAPPER_STFLD:
1978                 case MONO_WRAPPER_LDFLD_REMOTE:
1979                 case MONO_WRAPPER_STFLD_REMOTE:
1980                 case MONO_WRAPPER_ISINST: {
1981                         MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (patch_info->data.method);
1982                         encode_klass_info (acfg, proxy_class, p, &p);
1983                         break;
1984                 }
1985                 case MONO_WRAPPER_STELEMREF:
1986                         break;
1987                 default:
1988                         g_assert_not_reached ();
1989                 }
1990                 break;
1991         }
1992         default:
1993                 g_warning ("unable to handle jump info %d", patch_info->type);
1994                 g_assert_not_reached ();
1995         }
1996
1997         *endbuf = p;
1998 }
1999
2000 static void
2001 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2002 {
2003         MonoMethod *method;
2004         GList *l;
2005         int j, pindex, buf_size, n_patches;
2006         guint8 *code;
2007         char *symbol;
2008         GPtrArray *patches;
2009         MonoJumpInfo *patch_info;
2010         MonoMethodHeader *header;
2011         guint32 last_offset, method_idx;
2012         guint8 *p, *buf;
2013         guint32 first_got_offset;
2014
2015         method = cfg->method;
2016         code = cfg->native_code;
2017         header = mono_method_get_header (method);
2018
2019         method_idx = mono_metadata_token_index (method->token);
2020
2021         /* Make the labels local */
2022         symbol = g_strdup_printf (".Lm_%x_p", method_idx);
2023
2024         /* Sort relocations */
2025         patches = g_ptr_array_new ();
2026         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2027                 g_ptr_array_add (patches, patch_info);
2028         g_ptr_array_sort (patches, compare_patches);
2029
2030         first_got_offset = acfg->method_got_offsets [mono_metadata_token_index (cfg->method->token)];
2031
2032         /**********************/
2033         /* Encode method info */
2034         /**********************/
2035
2036         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2037         p = buf = g_malloc (buf_size);
2038
2039         if (mono_class_get_cctor (method->klass))
2040                 encode_klass_info (acfg, method->klass, p, &p);
2041         else
2042                 /* Not needed when loading the method */
2043                 encode_value (0, p, &p);
2044
2045         /* String table */
2046         if (cfg->opt & MONO_OPT_SHARED) {
2047                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2048                 for (l = cfg->ldstr_list; l; l = l->next) {
2049                         encode_value ((long)l->data, p, &p);
2050                 }
2051         }
2052         else
2053                 /* Used only in shared mode */
2054                 g_assert (!cfg->ldstr_list);
2055
2056         n_patches = 0;
2057         for (pindex = 0; pindex < patches->len; ++pindex) {
2058                 patch_info = g_ptr_array_index (patches, pindex);
2059                 
2060                 if ((patch_info->type == MONO_PATCH_INFO_LABEL) ||
2061                         (patch_info->type == MONO_PATCH_INFO_BB) ||
2062                         (patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2063                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
2064                         patch_info->type = MONO_PATCH_INFO_NONE;
2065                         /* Nothing to do */
2066                         continue;
2067                 }
2068
2069                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2070                         /* Stored in a GOT slot initialized at module load time */
2071                         patch_info->type = MONO_PATCH_INFO_NONE;
2072                         continue;
2073                 }
2074
2075                 n_patches ++;
2076         }
2077
2078         if (n_patches)
2079                 g_assert (acfg->has_got_slots [method_idx]);
2080
2081         encode_value (n_patches, p, &p);
2082
2083         if (n_patches)
2084                 encode_value (first_got_offset, p, &p);
2085
2086         /* First encode the type+position table */
2087         last_offset = 0;
2088         j = 0;
2089         for (pindex = 0; pindex < patches->len; ++pindex) {
2090                 guint32 offset;
2091                 patch_info = g_ptr_array_index (patches, pindex);
2092                 
2093                 if (patch_info->type == MONO_PATCH_INFO_NONE)
2094                         /* Nothing to do */
2095                         continue;
2096
2097                 j ++;
2098                 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
2099                 offset = patch_info->ip.i - last_offset;
2100                 last_offset = patch_info->ip.i;
2101
2102                 /* Only the type is needed */
2103                 *p = patch_info->type;
2104                 p++;
2105         }
2106
2107         /*
2108         if (n_patches) {
2109                 printf ("%s:\n", mono_method_full_name (cfg->method, TRUE));
2110                 for (pindex = 0; pindex < patches->len; ++pindex) {
2111                         patch_info = g_ptr_array_index (patches, pindex);
2112                         if (patch_info->type != MONO_PATCH_INFO_NONE) {
2113                                 printf ("\t%s", patch_types [patch_info->type]);
2114                                 if (patch_info->type == MONO_PATCH_INFO_VTABLE)
2115                                         printf (": %s\n", patch_info->data.klass->name);
2116                                 else
2117                                         printf ("\n");
2118                         }
2119                 }
2120         }
2121         */
2122
2123         /* Then encode the other info */
2124         for (pindex = 0; pindex < patches->len; ++pindex) {
2125                 patch_info = g_ptr_array_index (patches, pindex);
2126
2127                 encode_patch (acfg, patch_info, p, &p, TRUE);
2128         }
2129
2130         acfg->stats.info_size += p - buf;
2131
2132         /* Emit method info */
2133
2134         emit_label (acfg, symbol);
2135
2136         g_assert (p - buf < buf_size);
2137         emit_bytes (acfg, buf, p - buf);
2138         g_free (buf);
2139
2140         g_free (symbol);
2141 }
2142
2143 static void
2144 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2145 {
2146         MonoMethod *method;
2147         int k, buf_size;
2148         guint32 debug_info_size;
2149         guint8 *code;
2150         char *symbol;
2151         MonoMethodHeader *header;
2152         guint8 *p, *buf, *debug_info;
2153
2154         method = cfg->method;
2155         code = cfg->native_code;
2156         header = mono_method_get_header (method);
2157
2158         /* Make the labels local */
2159         symbol = g_strdup_printf (".Le_%x_p", mono_metadata_token_index (method->token));
2160
2161         buf_size = header->num_clauses * 256 + 128;
2162         p = buf = g_malloc (buf_size);
2163
2164         encode_value (cfg->code_len, p, &p);
2165         encode_value (cfg->used_int_regs, p, &p);
2166
2167         /* Exception table */
2168         if (header->num_clauses) {
2169                 MonoJitInfo *jinfo = cfg->jit_info;
2170
2171                 for (k = 0; k < header->num_clauses; ++k) {
2172                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2173
2174                         encode_value (ei->exvar_offset, p, &p);
2175
2176                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2177                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2178
2179                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2180                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2181                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2182                 }
2183         }
2184
2185         mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2186
2187         encode_value (debug_info_size, p, &p);
2188         if (debug_info_size) {
2189                 memcpy (p, debug_info, debug_info_size);
2190                 p += debug_info_size;
2191                 g_free (debug_info);
2192         }
2193
2194         acfg->stats.ex_info_size += p - buf;
2195
2196         /* Emit info */
2197
2198         emit_label (acfg, symbol);
2199
2200         g_assert (p - buf < buf_size);
2201         emit_bytes (acfg, buf, p - buf);
2202         g_free (buf);
2203
2204         g_free (symbol);
2205 }
2206
2207 static void
2208 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2209 {
2210         MonoClass *klass = mono_class_get (acfg->image, token);
2211         guint8 *p, *buf;
2212         int i, buf_size;
2213         char *label;
2214         gboolean no_special_static;
2215
2216         buf_size = 10240;
2217         p = buf = g_malloc (buf_size);
2218
2219         g_assert (klass);
2220
2221         mono_class_init (klass);
2222
2223         /* 
2224          * Emit all the information which is required for creating vtables so
2225          * the runtime does not need to create the MonoMethod structures which
2226          * take up a lot of space.
2227          */
2228
2229         no_special_static = !mono_class_has_special_static_fields (klass);
2230
2231         if (1) {
2232                 encode_value (klass->vtable_size, p, &p);
2233                 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);
2234                 if (klass->has_cctor)
2235                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2236                 if (klass->has_finalize)
2237                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2238  
2239                 encode_value (klass->instance_size, p, &p);
2240                 encode_value (mono_class_data_size (klass), p, &p);
2241                 encode_value (klass->packing_size, p, &p);
2242                 encode_value (klass->min_align, p, &p);
2243
2244                 for (i = 0; i < klass->vtable_size; ++i) {
2245                         MonoMethod *cm = klass->vtable [i];
2246
2247                         if (cm)
2248                                 encode_method_ref (acfg, cm, p, &p);
2249                         else
2250                                 encode_value (0, p, &p);
2251                 }
2252         }
2253
2254         acfg->stats.class_info_size += p - buf;
2255
2256         /* Emit the info */
2257         label = g_strdup_printf (".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2258         emit_label (acfg, label);
2259
2260         g_assert (p - buf < buf_size);
2261         emit_bytes (acfg, buf, p - buf);
2262         g_free (buf);
2263 }
2264
2265 /*
2266  * Calls made from AOTed code are routed through a table of jumps similar to the
2267  * ELF PLT (Program Linkage Table). The differences are the following:
2268  * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2269  *   GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2270  *   jumps. This means the jumps need to be patched when the address of the callee is
2271  *   known. Initially the PLT entries jump to code which transfer control to the
2272  *   AOT runtime through the first PLT entry.
2273  */
2274 static void
2275 emit_plt (MonoAotCompile *acfg)
2276 {
2277         char *symbol;
2278         int i, buf_size;
2279         guint8 *p, *buf;
2280         guint32 *plt_info_offsets;
2281
2282         /*
2283          * Encode info need to resolve PLT entries.
2284          */
2285         buf_size = acfg->plt_offset * 128;
2286         p = buf = g_malloc (buf_size);
2287
2288         plt_info_offsets = g_new0 (guint32, acfg->plt_offset);
2289
2290         for (i = 1; i < acfg->plt_offset; ++i) {
2291                 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
2292
2293                 plt_info_offsets [i] = p - buf;
2294                 encode_value (patch_info->type, p, &p);
2295                 encode_patch (acfg, patch_info, p, &p, FALSE);
2296         }
2297
2298         emit_line (acfg);
2299         symbol = g_strdup_printf ("plt");
2300
2301         /* This section will be made read-write by the AOT loader */
2302         emit_section_change (acfg, ".text", 0);
2303         emit_global (acfg, symbol, TRUE);
2304         emit_alignment (acfg, PAGESIZE);
2305         emit_label (acfg, symbol);
2306
2307         /* 
2308          * The first plt entry is used to transfer code to the AOT loader. 
2309          */
2310         emit_label (acfg, ".Lp_0");
2311 #if defined(__i386__)
2312         /* It is filled up during loading by the AOT loader. */
2313         emit_zero_bytes (acfg, 16);
2314 #elif defined(__x86_64__)
2315         /* This should be exactly 16 bytes long */
2316         /* jmpq *<offset>(%rip) */
2317         emit_byte (acfg, '\xff');
2318         emit_byte (acfg, '\x25');
2319         emit_symbol_diff (acfg, "plt_jump_table", ".", -4);
2320         emit_zero_bytes (acfg, 10);
2321 #else
2322         g_assert_not_reached ();
2323 #endif
2324
2325         for (i = 1; i < acfg->plt_offset; ++i) {
2326                 char *label;
2327
2328                 label = g_strdup_printf (".Lp_%d", i);
2329                 emit_label (acfg, label);
2330                 g_free (label);
2331 #if defined(__i386__)
2332                 /* Need to make sure this is 5 bytes long */
2333                 emit_byte (acfg, '\xe9');
2334                 label = g_strdup_printf (".Lpd_%d", i);
2335                 emit_symbol_diff (acfg, label, ".", -4);
2336                 g_free (label);
2337 #elif defined(__x86_64__)
2338                 /*
2339                  * We can't emit jumps because they are 32 bits only so they can't be patched.
2340                  * So we emit a jump table instead whose entries are patched by the AOT loader to
2341                  * point to .Lpd entries. ELF stores these in the GOT too, but we don't, since
2342                  * methods with GOT entries can't be called directly.
2343                  * We also emit the default PLT code here since the PLT code will not be patched.
2344                  * An x86_64 plt entry is 16 bytes long, init_plt () depends on this.
2345                  */
2346                 /* jmpq *<offset>(%rip) */
2347                 emit_byte (acfg, '\xff');
2348                 emit_byte (acfg, '\x25');
2349                 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)) -4);
2350                 /* mov <plt info offset>, %eax */
2351                 emit_byte (acfg, '\xb8');
2352                 emit_int32 (acfg, plt_info_offsets [i]);
2353                 /* jmp .Lp_0 */
2354                 emit_byte (acfg, '\xe9');
2355                 emit_symbol_diff (acfg, ".Lp_0", ".", -4);
2356 #else
2357                 g_assert_not_reached ();
2358 #endif
2359         }
2360
2361         symbol = g_strdup_printf ("plt_end");
2362         emit_global (acfg, symbol, TRUE);
2363         emit_label (acfg, symbol);
2364
2365         /* 
2366          * Emit the default targets for the PLT entries separately since these will not
2367          * be modified at runtime.
2368          */
2369         for (i = 1; i < acfg->plt_offset; ++i) {
2370                 char *label;
2371
2372                 label = g_strdup_printf (".Lpd_%d", i);
2373                 emit_label (acfg, label);
2374                 g_free (label);
2375
2376                 /* Put the offset into the register expected by mono_aot_plt_trampoline */
2377 #if defined(__i386__)
2378                 /* movl $const, %eax */
2379                 emit_byte (acfg, '\xb8');
2380                 emit_int32 (acfg, plt_info_offsets [i]);
2381                 /* jmp .Lp_0 */
2382                 emit_byte (acfg, '\xe9');
2383                 emit_symbol_diff (acfg, ".Lp_0", ".", -4);
2384 #elif defined(__x86_64__)
2385                 /* Emitted along with the PLT entries since they will not be patched */
2386 #else
2387                 g_assert_not_reached ();
2388 #endif
2389         }
2390
2391         /* Emit PLT info */
2392         symbol = g_strdup_printf ("plt_info");
2393         emit_global (acfg, symbol, FALSE);
2394         emit_label (acfg, symbol);
2395
2396         g_assert (p - buf < buf_size);
2397         emit_bytes (acfg, buf, p - buf);
2398         g_free (buf);
2399
2400         symbol = g_strdup_printf ("plt_jump_table_addr");
2401         emit_section_change (acfg, ".data", 0);
2402         emit_global (acfg, symbol, FALSE);
2403         emit_alignment (acfg, 8);
2404         emit_label (acfg, symbol);
2405         emit_pointer (acfg, "plt_jump_table");
2406
2407         symbol = g_strdup_printf ("plt_jump_table_size");
2408         emit_section_change (acfg, ".data", 0);
2409         emit_global (acfg, symbol, FALSE);
2410         emit_alignment (acfg, 8);
2411         emit_label (acfg, symbol);
2412         emit_symbol_diff (acfg, "plt_jump_table_end", "plt_jump_table", 0);
2413
2414         /* Don't make this a global so accesses don't need relocations */
2415         symbol = g_strdup_printf ("plt_jump_table");
2416         emit_section_change (acfg, ".bss", 0);
2417         emit_label (acfg, symbol);
2418
2419 #ifdef __x86_64__
2420         emit_zero_bytes (acfg, (int)(acfg->plt_offset * sizeof (gpointer)));
2421 #endif  
2422
2423         symbol = g_strdup_printf ("plt_jump_table_end");
2424         emit_label (acfg, symbol);
2425 }
2426
2427 static gboolean
2428 str_begins_with (const char *str1, const char *str2)
2429 {
2430         int len = strlen (str2);
2431         return strncmp (str1, str2, len) == 0;
2432 }
2433
2434 static void
2435 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
2436 {
2437         gchar **args, **ptr;
2438
2439         memset (opts, 0, sizeof (*opts));
2440
2441         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
2442         for (ptr = args; ptr && *ptr; ptr ++) {
2443                 const char *arg = *ptr;
2444
2445                 if (str_begins_with (arg, "outfile=")) {
2446                         opts->outfile = g_strdup (arg + strlen ("outfile="));
2447                 } else if (str_begins_with (arg, "save-temps")) {
2448                         opts->save_temps = TRUE;
2449                 } else if (str_begins_with (arg, "keep-temps")) {
2450                         opts->save_temps = TRUE;
2451                 } else if (str_begins_with (arg, "write-symbols")) {
2452                         opts->write_symbols = TRUE;
2453                 } else if (str_begins_with (arg, "metadata-only")) {
2454                         opts->metadata_only = TRUE;
2455                 } else {
2456                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
2457                         exit (1);
2458                 }
2459         }
2460 }
2461
2462 static void
2463 compile_method (MonoAotCompile *acfg, int index)
2464 {
2465         MonoCompile *cfg;
2466         MonoMethod *method;
2467         MonoJumpInfo *patch_info;
2468         gboolean skip;
2469         guint32 token = MONO_TOKEN_METHOD_DEF | (index + 1);
2470         guint32 method_idx;
2471
2472         if (acfg->aot_opts.metadata_only)
2473                 return;
2474
2475         method = mono_get_method (acfg->image, token, NULL);
2476
2477         method_idx = mono_metadata_token_index (method->token); 
2478                 
2479         /* fixme: maybe we can also precompile wrapper methods */
2480         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2481                 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2482                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2483                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
2484                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
2485                 return;
2486         }
2487
2488         acfg->stats.mcount++;
2489
2490         /* fixme: we need to patch the IP for the LMF in that case */
2491         if (method->save_lmf) {
2492                 //printf ("Skip (needs lmf):  %s\n", mono_method_full_name (method, TRUE));
2493                 acfg->stats.lmfcount++;
2494                 return;
2495         }
2496
2497         /*
2498          * Since these methods are the only ones which are compiled with
2499          * AOT support, and they are not used by runtime startup/shutdown code,
2500          * the runtime will not see AOT methods during AOT compilation,so it
2501          * does not need to support them by creating a fake GOT etc.
2502          */
2503         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
2504         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
2505                 /* Let the exception happen at runtime */
2506                 return;
2507         }
2508
2509         if (cfg->disable_aot) {
2510                 //printf ("Skip (other): %s\n", mono_method_full_name (method, TRUE));
2511                 acfg->stats.ocount++;
2512                 mono_destroy_compile (cfg);
2513                 return;
2514         }
2515
2516         skip = FALSE;
2517         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2518                 if (patch_info->type == MONO_PATCH_INFO_ABS) {
2519                         /* unable to handle this */
2520                         //printf ("Skip (abs addr):   %s %d\n", mono_method_full_name (method, TRUE), patch_info->type);
2521                         skip = TRUE;    
2522                         break;
2523                 }
2524         }
2525
2526         if (skip) {
2527                 acfg->stats.abscount++;
2528                 mono_destroy_compile (cfg);
2529                 return;
2530         }
2531
2532         skip = FALSE;
2533         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2534                 if (patch_info->type == MONO_PATCH_INFO_METHOD_JUMP) {
2535                         /* 
2536                          * FIXME: We can't handle this because mono_jit_compile_method_inner will try
2537                          * to patch the AOT code when the target of the jump is compiled.
2538                          */
2539                         skip = TRUE;
2540                         break;
2541                 }
2542         }
2543
2544         if (skip) {
2545                 acfg->stats.ocount++;
2546                 mono_destroy_compile (cfg);
2547                 return;
2548         }
2549
2550         /* some wrappers are very common */
2551         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2552                 if (patch_info->type == MONO_PATCH_INFO_METHODCONST) {
2553                         switch (patch_info->data.method->wrapper_type) {
2554                         case MONO_WRAPPER_PROXY_ISINST:
2555                                 patch_info->type = MONO_PATCH_INFO_WRAPPER;
2556                         }
2557                 }
2558
2559                 if (patch_info->type == MONO_PATCH_INFO_METHOD) {
2560                         switch (patch_info->data.method->wrapper_type) {
2561                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2562                         case MONO_WRAPPER_STFLD:
2563                         case MONO_WRAPPER_LDFLD:
2564                         case MONO_WRAPPER_LDFLDA:
2565                         case MONO_WRAPPER_LDFLD_REMOTE:
2566                         case MONO_WRAPPER_STFLD_REMOTE:
2567                         case MONO_WRAPPER_STELEMREF:
2568                         case MONO_WRAPPER_ISINST:
2569                         case MONO_WRAPPER_PROXY_ISINST:
2570                                 patch_info->type = MONO_PATCH_INFO_WRAPPER;
2571                                 break;
2572                         }
2573                 }
2574         }
2575
2576         skip = FALSE;
2577         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2578                 switch (patch_info->type) {
2579                 case MONO_PATCH_INFO_METHOD:
2580                 case MONO_PATCH_INFO_METHODCONST:
2581                         if (patch_info->data.method->wrapper_type) {
2582                                 /* unable to handle this */
2583                                 //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));
2584                                 skip = TRUE;
2585                                 break;
2586                         }
2587                         if (!patch_info->data.method->token)
2588                                 /*
2589                                  * The method is part of a constructed type like Int[,].Set (). It doesn't
2590                                  * have a token, and we can't make one, since the parent type is part of
2591                                  * assembly which contains the element type, and not the assembly which
2592                                  * referenced this type.
2593                                  */
2594                                 skip = TRUE;
2595                         break;
2596                 case MONO_PATCH_INFO_VTABLE:
2597                 case MONO_PATCH_INFO_CLASS_INIT:
2598                 case MONO_PATCH_INFO_CLASS:
2599                 case MONO_PATCH_INFO_IID:
2600                 case MONO_PATCH_INFO_ADJUSTED_IID:
2601                         if (!patch_info->data.klass->type_token)
2602                                 if (!patch_info->data.klass->element_class->type_token)
2603                                         skip = TRUE;
2604                         break;
2605                 default:
2606                         break;
2607                 }
2608         }
2609
2610         if (skip) {
2611                 acfg->stats.wrappercount++;
2612                 mono_destroy_compile (cfg);
2613                 return;
2614         }
2615
2616         /* Determine whenever the method has GOT slots */
2617         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2618                 switch (patch_info->type) {
2619                 case MONO_PATCH_INFO_LABEL:
2620                 case MONO_PATCH_INFO_BB:
2621                 case MONO_PATCH_INFO_GOT_OFFSET:
2622                 case MONO_PATCH_INFO_NONE:
2623                 case MONO_PATCH_INFO_METHOD:
2624                 case MONO_PATCH_INFO_INTERNAL_METHOD:
2625                 case MONO_PATCH_INFO_WRAPPER:
2626                         break;
2627                 case MONO_PATCH_INFO_IMAGE:
2628                         if (patch_info->data.image == acfg->image)
2629                                 /* Stored in GOT slot 0 */
2630                                 break;
2631                         /* Fall through */
2632                 default:
2633                         acfg->has_got_slots [method_idx] = TRUE;
2634                         break;
2635                 }
2636         }
2637
2638         if (!acfg->has_got_slots [method_idx])
2639                 acfg->stats.methods_without_got_slots ++;
2640
2641         /* Make a copy of the patch info which is in the mempool */
2642         {
2643                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
2644
2645                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2646                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2647
2648                         if (!patches)
2649                                 patches = new_patch_info;
2650                         else
2651                                 patches_end->next = new_patch_info;
2652                         patches_end = new_patch_info;
2653                 }
2654                 cfg->patch_info = patches;
2655         }
2656
2657         /* Free some fields used by cfg to conserve memory */
2658         mono_mempool_destroy (cfg->mempool);
2659         cfg->mempool = NULL;
2660         g_free (cfg->varinfo);
2661         cfg->varinfo = NULL;
2662         g_free (cfg->vars);
2663         cfg->vars = NULL;
2664         if (cfg->rs) {
2665                 mono_regstate_free (cfg->rs);
2666                 cfg->rs = NULL;
2667         }
2668
2669         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
2670
2671         acfg->cfgs [index] = cfg;
2672
2673         g_hash_table_insert (acfg->method_to_cfg, cfg->method, cfg);
2674
2675         acfg->stats.ccount++;
2676 }
2677
2678 static void
2679 load_profile_files (MonoAotCompile *acfg)
2680 {
2681         FILE *infile;
2682         char *tmp;
2683         int file_index, res, method_index, i;
2684         char ver [256];
2685         guint32 token;
2686
2687         file_index = 0;
2688         while (TRUE) {
2689                 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);
2690
2691                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR))
2692                         break;
2693
2694                 infile = fopen (tmp, "r");
2695                 g_assert (infile);
2696
2697                 printf ("Using profile data file '%s'\n", tmp);
2698
2699                 file_index ++;
2700
2701                 res = fscanf (infile, "%32s\n", ver);
2702                 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
2703                         printf ("Profile file has wrong version or invalid.\n");
2704                         continue;
2705                 }
2706
2707                 while (TRUE) {
2708                         res = fscanf (infile, "%d\n", &token);
2709                         if (res < 1)
2710                                 break;
2711
2712                         method_index = mono_metadata_token_index (token) - 1;
2713
2714                         if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
2715                                 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
2716                 }
2717         }
2718
2719         /* Add missing methods */
2720         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2721                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
2722                         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (i));
2723         }               
2724 }
2725
2726 /**
2727  * alloc_got_slots:
2728  *
2729  *  Collect all patches which have shared GOT entries and alloc entries for them. The
2730  * rest will get entries allocated during emit_code ().
2731  */
2732 static void
2733 alloc_got_slots (MonoAotCompile *acfg)
2734 {
2735         int i;
2736         GList *l;
2737         MonoJumpInfo *ji;
2738
2739         /* Slot 0 is reserved for the address of the current assembly */
2740         ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
2741         ji->type = MONO_PATCH_INFO_IMAGE;
2742         ji->data.image = acfg->image;
2743
2744         get_shared_got_offset (acfg, ji);
2745
2746         for (l = acfg->method_order; l != NULL; l = l->next) {
2747                 i = GPOINTER_TO_UINT (l->data);
2748
2749                 if (acfg->cfgs [i]) {
2750                         MonoCompile *cfg = acfg->cfgs [i];
2751
2752                         for (ji = cfg->patch_info; ji; ji = ji->next) {
2753                                 switch (ji->type) {
2754                                 case MONO_PATCH_INFO_VTABLE:
2755                                 case MONO_PATCH_INFO_CLASS:
2756                                 case MONO_PATCH_INFO_IID:
2757                                 case MONO_PATCH_INFO_ADJUSTED_IID:
2758                                 case MONO_PATCH_INFO_FIELD:
2759                                 case MONO_PATCH_INFO_SFLDA:
2760                                 case MONO_PATCH_INFO_DECLSEC:
2761                                 case MONO_PATCH_INFO_LDTOKEN:
2762                                 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2763                                         get_shared_got_offset (acfg, ji);
2764                                         break;
2765                                 default:
2766                                         break;
2767                                 }
2768                         }
2769                 }
2770         }
2771 }
2772
2773 static void
2774 emit_code (MonoAotCompile *acfg)
2775 {
2776         int i;
2777         char *symbol;
2778         GList *l;
2779
2780         symbol = g_strdup_printf ("methods");
2781         emit_section_change (acfg, ".text", 0);
2782         emit_global (acfg, symbol, TRUE);
2783         emit_alignment (acfg, 8);
2784         emit_label (acfg, symbol);
2785
2786         for (l = acfg->method_order; l != NULL; l = l->next) {
2787                 i = GPOINTER_TO_UINT (l->data);
2788
2789                 if (acfg->cfgs [i])
2790                         emit_method_code (acfg, acfg->cfgs [i]);
2791         }
2792
2793         symbol = g_strdup_printf ("methods_end");
2794         emit_section_change (acfg, ".text", 0);
2795         emit_global (acfg, symbol, FALSE);
2796         emit_alignment (acfg, 8);
2797         emit_label (acfg, symbol);
2798
2799         symbol = g_strdup_printf ("method_offsets");
2800         emit_section_change (acfg, ".text", 1);
2801         emit_global (acfg, symbol, FALSE);
2802         emit_alignment (acfg, 8);
2803         emit_label (acfg, symbol);
2804
2805         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2806                 if (acfg->cfgs [i]) {
2807                         symbol = g_strdup_printf (".Lm_%x", i + 1);
2808                         emit_symbol_diff (acfg, symbol, "methods", 0);
2809                 } else {
2810                         emit_int32 (acfg, 0xffffffff);
2811                 }
2812         }
2813         emit_line (acfg);
2814 }
2815
2816 static void
2817 emit_info (MonoAotCompile *acfg)
2818 {
2819         int i;
2820         char *symbol;
2821         GList *l;
2822
2823         /* Emit method info */
2824         symbol = g_strdup_printf ("method_info");
2825         emit_section_change (acfg, ".text", 1);
2826         emit_global (acfg, symbol, FALSE);
2827         emit_alignment (acfg, 8);
2828         emit_label (acfg, symbol);
2829
2830         /* To reduce size of generated assembly code */
2831         symbol = g_strdup_printf ("mi");
2832         emit_label (acfg, symbol);
2833
2834         for (l = acfg->method_order; l != NULL; l = l->next) {
2835                 i = GPOINTER_TO_UINT (l->data);
2836
2837                 if (acfg->cfgs [i])
2838                         emit_method_info (acfg, acfg->cfgs [i]);
2839         }
2840
2841         symbol = g_strdup_printf ("method_info_offsets");
2842         emit_section_change (acfg, ".text", 1);
2843         emit_global (acfg, symbol, FALSE);
2844         emit_alignment (acfg, 8);
2845         emit_label (acfg, symbol);
2846
2847         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2848                 if (acfg->cfgs [i]) {
2849                         symbol = g_strdup_printf (".Lm_%x_p", i + 1);
2850                         emit_symbol_diff (acfg, symbol, "mi", 0);
2851                 } else {
2852                         emit_int32 (acfg, 0);
2853                 }
2854         }
2855         emit_line (acfg);
2856 }
2857
2858 static void
2859 emit_method_order (MonoAotCompile *acfg)
2860 {
2861         int i, index, len;
2862         char *symbol;
2863         GList *l;
2864
2865         symbol = g_strdup_printf ("method_order");
2866         emit_section_change (acfg, ".text", 1);
2867         emit_global (acfg, symbol, FALSE);
2868         emit_alignment (acfg, 8);
2869         emit_label (acfg, symbol);
2870
2871         /* First emit an index table */
2872         index = 0;
2873         len = 0;
2874         for (l = acfg->method_order; l != NULL; l = l->next) {
2875                 i = GPOINTER_TO_UINT (l->data);
2876
2877                 if (acfg->cfgs [i]) {
2878                         if ((index % 1024) == 0) {
2879                                 emit_int32 (acfg, i);
2880                         }
2881
2882                         index ++;
2883                 }
2884
2885                 len ++;
2886         }
2887         emit_int32 (acfg, 0xffffff);
2888
2889         /* Then emit the whole method order */
2890         for (l = acfg->method_order; l != NULL; l = l->next) {
2891                 i = GPOINTER_TO_UINT (l->data);
2892
2893                 if (acfg->cfgs [i]) {
2894                         emit_int32 (acfg, i);
2895                 }
2896         }       
2897         emit_line (acfg);
2898
2899         symbol = g_strdup_printf ("method_order_end");
2900         emit_section_change (acfg, ".text", 1);
2901         emit_global (acfg, symbol, FALSE);
2902         emit_label (acfg, symbol);
2903 }
2904
2905 static void
2906 emit_exception_info (MonoAotCompile *acfg)
2907 {
2908         int i;
2909         char *symbol;
2910
2911         symbol = g_strdup_printf ("ex_info");
2912         emit_section_change (acfg, ".text", 1);
2913         emit_global (acfg, symbol, FALSE);
2914         emit_alignment (acfg, 8);
2915         emit_label (acfg, symbol);
2916
2917         /* To reduce size of generate assembly */
2918         symbol = g_strdup_printf ("ex");
2919         emit_label (acfg, symbol);
2920
2921         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2922                 if (acfg->cfgs [i])
2923                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
2924         }
2925
2926         symbol = g_strdup_printf ("ex_info_offsets");
2927         emit_section_change (acfg, ".text", 1);
2928         emit_global (acfg, symbol, FALSE);
2929         emit_alignment (acfg, 8);
2930         emit_label (acfg, symbol);
2931
2932         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2933                 if (acfg->cfgs [i]) {
2934                         symbol = g_strdup_printf (".Le_%x_p", i + 1);
2935                         emit_symbol_diff (acfg, symbol, "ex", 0);
2936                 } else {
2937                         emit_int32 (acfg, 0);
2938                 }
2939         }
2940         emit_line (acfg);
2941 }
2942
2943 static void
2944 emit_class_info (MonoAotCompile *acfg)
2945 {
2946         int i;
2947         char *symbol;
2948
2949         symbol = g_strdup_printf ("class_info");
2950         emit_section_change (acfg, ".text", 1);
2951         emit_global (acfg, symbol, FALSE);
2952         emit_alignment (acfg, 8);
2953         emit_label (acfg, symbol);
2954
2955         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
2956                 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
2957
2958         symbol = g_strdup_printf ("class_info_offsets");
2959         emit_section_change (acfg, ".text", 1);
2960         emit_global (acfg, symbol, FALSE);
2961         emit_alignment (acfg, 8);
2962         emit_label (acfg, symbol);
2963
2964         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2965                 symbol = g_strdup_printf (".LK_I_%x", i);
2966                 emit_symbol_diff (acfg, symbol, "class_info", 0);
2967         }
2968         emit_line (acfg);
2969 }
2970
2971 typedef struct ClassNameTableEntry {
2972         guint32 token, index;
2973         struct ClassNameTableEntry *next;
2974 } ClassNameTableEntry;
2975
2976 static void
2977 emit_class_name_table (MonoAotCompile *acfg)
2978 {
2979         int i, table_size;
2980         guint32 token, hash;
2981         MonoClass *klass;
2982         GPtrArray *table;
2983         char *full_name;
2984         char *symbol;
2985         ClassNameTableEntry *entry, *new_entry;
2986
2987         /*
2988          * Construct a chained hash table for mapping class names to typedef tokens.
2989          */
2990         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
2991         table = g_ptr_array_sized_new (table_size);
2992         for (i = 0; i < table_size; ++i)
2993                 g_ptr_array_add (table, NULL);
2994         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2995                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2996                 klass = mono_class_get (acfg->image, token);
2997                 full_name = mono_type_get_full_name (klass);
2998                 hash = g_str_hash (full_name) % table_size;
2999
3000                 //printf ("A: '%s' %d %d\n", full_name, g_str_hash (full_name), hash);
3001
3002                 /* FIXME: Allocate from the mempool */
3003                 new_entry = g_new0 (ClassNameTableEntry, 1);
3004                 new_entry->token = token;
3005
3006                 entry = g_ptr_array_index (table, hash);
3007                 if (entry == NULL) {
3008                         new_entry->index = hash;
3009                         g_ptr_array_index (table, hash) = new_entry;
3010                 } else {
3011                         while (entry->next)
3012                                 entry = entry->next;
3013                         
3014                         entry->next = new_entry;
3015                         new_entry->index = table->len;
3016                         g_ptr_array_add (table, new_entry);
3017                 }
3018         }
3019
3020         /* Emit the table */
3021         symbol = g_strdup_printf ("class_name_table");
3022         emit_section_change (acfg, ".text", 0);
3023         emit_global (acfg, symbol, FALSE);
3024         emit_alignment (acfg, 8);
3025         emit_label (acfg, symbol);
3026
3027         /* FIXME: Optimize memory usage */
3028         emit_int32 (acfg, table_size);
3029         for (i = 0; i < table->len; ++i) {
3030                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
3031
3032                 if (entry == NULL) {
3033                         emit_int32 (acfg, 0);
3034                         emit_int32 (acfg, 0);
3035                 } else {
3036                         emit_int32 (acfg, entry->token);
3037                         if (entry->next)
3038                                 emit_int32 (acfg, entry->next->index);
3039                         else
3040                                 emit_int32 (acfg, 0);
3041                 }
3042         }
3043 }
3044
3045 static void
3046 emit_image_table (MonoAotCompile *acfg)
3047 {
3048         int i;
3049         char *symbol;
3050
3051         /*
3052          * The image table is small but referenced in a lot of places.
3053          * So we emit it at once, and reference its elements by an index.
3054          */
3055
3056         symbol = g_strdup_printf ("mono_image_table");
3057         emit_section_change (acfg, ".text", 1);
3058         emit_global (acfg, symbol, FALSE);
3059         emit_alignment (acfg, 8);
3060         emit_label (acfg, symbol);
3061         emit_int32 (acfg, acfg->image_table->len);
3062         for (i = 0; i < acfg->image_table->len; i++) {
3063                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
3064                 MonoAssemblyName *aname = &image->assembly->aname;
3065
3066                 /* FIXME: Support multi-module assemblies */
3067                 g_assert (image->assembly->image == image);
3068
3069                 emit_string (acfg, image->assembly_name);
3070                 emit_string (acfg, image->guid);
3071                 emit_string (acfg, aname->culture ? aname->culture : "");
3072                 emit_string (acfg, (const char*)aname->public_key_token);
3073
3074                 emit_alignment (acfg, 8);
3075                 emit_int32 (acfg, aname->flags);
3076                 emit_int32 (acfg, aname->major);
3077                 emit_int32 (acfg, aname->minor);
3078                 emit_int32 (acfg, aname->build);
3079                 emit_int32 (acfg, aname->revision);
3080         }
3081 }
3082
3083 static void
3084 emit_got_info (MonoAotCompile *acfg)
3085 {
3086         char *symbol;
3087         int i, buf_size;
3088         guint8 *p, *buf;
3089         guint32 *got_info_offsets;
3090
3091         /**
3092          * FIXME: 
3093          * - optimize offsets table.
3094          * - reduce number of exported symbols.
3095          * - emit info for a klass only once.
3096          * - determine when a method uses a GOT slot which is guaranteed to be already 
3097          *   initialized.
3098          * - clean up and document the code.
3099          * - use String.Empty in class libs.
3100          */
3101
3102         /* Encode info required to decode shared GOT entries */
3103         buf_size = acfg->shared_patches->len * 64;
3104         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
3105         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
3106         for (i = 0; i < acfg->shared_patches->len; ++i) {
3107                 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
3108
3109                 /* No need to encode the patch type */
3110                 got_info_offsets [i] = p - buf;
3111                 encode_patch (acfg, ji, p, &p, FALSE);
3112         }
3113
3114         g_assert (p - buf <= buf_size);
3115
3116         acfg->stats.got_info_size = p - buf;
3117
3118         /* Emit got_info table */
3119         symbol = g_strdup_printf ("got_info");
3120         emit_section_change (acfg, ".text", 1);
3121         emit_global (acfg, symbol, FALSE);
3122         emit_alignment (acfg, 8);
3123         emit_label (acfg, symbol);
3124
3125         emit_bytes (acfg, buf, p - buf);
3126
3127         /* Emit got_info_offsets table */
3128         symbol = g_strdup_printf ("got_info_offsets");
3129         emit_section_change (acfg, ".text", 1);
3130         emit_global (acfg, symbol, FALSE);
3131         emit_alignment (acfg, 8);
3132         emit_label (acfg, symbol);
3133
3134         for (i = 0; i < acfg->shared_patches->len; ++i)
3135                 emit_int32 (acfg, got_info_offsets [i]);
3136
3137         acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
3138 }
3139
3140 static void
3141 emit_got (MonoAotCompile *acfg)
3142 {
3143         char *symbol;
3144
3145         /* Don't make GOT global so accesses to it don't need relocations */
3146         symbol = g_strdup_printf ("got");
3147         emit_section_change (acfg, ".bss", 1);
3148         emit_alignment (acfg, 8);
3149         emit_label (acfg, symbol);
3150         if (acfg->got_offset > 0)
3151                 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
3152
3153         symbol = g_strdup_printf ("got_addr");
3154         emit_section_change (acfg, ".data", 1);
3155         emit_global (acfg, symbol, FALSE);
3156         emit_alignment (acfg, 8);
3157         emit_label (acfg, symbol);
3158         emit_pointer (acfg, "got");
3159
3160         symbol = g_strdup_printf ("got_size");
3161         emit_section_change (acfg, ".data", 1);
3162         emit_global (acfg, symbol, FALSE);
3163         emit_alignment (acfg, 8);
3164         emit_label (acfg, symbol);
3165         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
3166 }
3167
3168 static void
3169 emit_globals (MonoAotCompile *acfg)
3170 {
3171         char *opts_str;
3172
3173         emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
3174
3175         emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
3176
3177         opts_str = g_strdup_printf ("%d", acfg->opts);
3178         emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
3179         g_free (opts_str);
3180 }
3181
3182 int
3183 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
3184 {
3185         MonoImage *image = ass->image;
3186         char *symbol;
3187         int i;
3188         MonoAotCompile *acfg;
3189         MonoCompile **cfgs;
3190
3191         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
3192
3193         acfg = g_new0 (MonoAotCompile, 1);
3194         acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
3195         acfg->patch_to_plt_offset = g_hash_table_new (NULL, NULL);
3196         acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3197         acfg->shared_patches = g_ptr_array_new ();
3198         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
3199         acfg->image_hash = g_hash_table_new (NULL, NULL);
3200         acfg->image_table = g_ptr_array_new ();
3201         acfg->image = image;
3202         acfg->opts = opts;
3203         acfg->mempool = mono_mempool_new ();
3204
3205         mono_aot_parse_options (aot_options, &acfg->aot_opts);
3206
3207         load_profile_files (acfg);
3208
3209         if (mono_defaults.generic_nullable_class) {
3210                 /* 
3211                  * FIXME: Its hard to skip generic methods or methods which use generics.
3212                  */
3213                 printf ("Error: Can't AOT Net 2.0 assemblies.\n");
3214                 return 1;
3215         }
3216
3217         emit_start (acfg);
3218
3219         cfgs = g_new0 (MonoCompile*, image->tables [MONO_TABLE_METHOD].rows + 32);
3220         acfg->cfgs = cfgs;
3221         acfg->nmethods = image->tables [MONO_TABLE_METHOD].rows;
3222         acfg->method_got_offsets = g_new0 (guint32, image->tables [MONO_TABLE_METHOD].rows + 32);
3223         acfg->has_got_slots = g_new0 (gboolean, image->tables [MONO_TABLE_METHOD].rows + 32);
3224
3225         /* PLT offset 0 is reserved for the PLT trampoline */
3226         acfg->plt_offset = 1;
3227
3228         /* Compile methods */
3229         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i)
3230                 compile_method (acfg, i);
3231
3232         alloc_got_slots (acfg);
3233
3234         emit_code (acfg);
3235
3236         emit_info (acfg);
3237
3238         emit_method_order (acfg);
3239
3240         emit_class_name_table (acfg);
3241
3242         emit_got_info (acfg);
3243
3244         emit_exception_info (acfg);
3245
3246         emit_class_info (acfg);
3247
3248         emit_plt (acfg);
3249
3250         emit_image_table (acfg);
3251
3252         emit_got (acfg);
3253
3254         emit_globals (acfg);
3255
3256         symbol = g_strdup_printf ("mem_end");
3257         emit_section_change (acfg, ".text", 1);
3258         emit_global (acfg, symbol, FALSE);
3259         emit_alignment (acfg, 8);
3260         emit_label (acfg, symbol);
3261
3262         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)));
3263
3264         emit_writeout (acfg);
3265
3266         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);
3267         printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
3268         printf ("%d methods contain wrapper references (%d%%)\n", acfg->stats.wrappercount, acfg->stats.mcount ? (acfg->stats.wrappercount * 100) / acfg->stats.mcount : 100);
3269         printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
3270         printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
3271         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);
3272         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
3273
3274         printf ("GOT slot distribution:\n");
3275         for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
3276                 if (acfg->stats.got_slot_types [i])
3277                         printf ("\t%s: %d\n", patch_types [i], acfg->stats.got_slot_types [i]);
3278
3279         return 0;
3280 }
3281
3282 #else
3283
3284 /* AOT disabled */
3285
3286 int
3287 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
3288 {
3289         return 0;
3290 }
3291
3292 #endif