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