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