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