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