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