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 if (token == 0) {
1726                 /* This might be a method of a constructed type like int[,].Set */
1727                 /* Obtain the token from information recorded by the JIT */
1728                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1729                 g_assert (ji);
1730                 image_index = get_image_index (acfg, ji->image);
1731                 g_assert (image_index < 255);
1732                 token = ji->token;
1733
1734                 /* Marker */
1735                 encode_value ((255 << 24), buf, &buf);
1736                 encode_value (image_index, buf, &buf);
1737                 encode_value (token, buf, &buf);
1738         } else {
1739                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1740                 encode_value ((image_index << 24) | mono_metadata_token_index (token), buf, &buf);
1741         }
1742         *endbuf = buf;
1743 }
1744
1745 static gint
1746 compare_patches (gconstpointer a, gconstpointer b)
1747 {
1748         int i, j;
1749
1750         i = (*(MonoJumpInfo**)a)->ip.i;
1751         j = (*(MonoJumpInfo**)b)->ip.i;
1752
1753         if (i < j)
1754                 return -1;
1755         else
1756                 if (i > j)
1757                         return 1;
1758         else
1759                 return 0;
1760 }
1761
1762 static int
1763 get_plt_index (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1764 {
1765         int res = -1;
1766         int idx;
1767         GHashTable *hash = acfg->patch_to_plt_offset;
1768
1769         switch (patch_info->type) {
1770         case MONO_PATCH_INFO_METHOD:
1771         case MONO_PATCH_INFO_WRAPPER:
1772         case MONO_PATCH_INFO_INTERNAL_METHOD:
1773         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1774         case MONO_PATCH_INFO_CLASS_INIT: {
1775                 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1776                 gpointer patch_id = NULL;
1777
1778                 /* First check for an existing patch */
1779                 switch (patch_info->type) {
1780                 case MONO_PATCH_INFO_METHOD:
1781                         patch_id = patch_info->data.method;
1782                         break;
1783                 case MONO_PATCH_INFO_INTERNAL_METHOD:
1784                         patch_id = (gpointer)patch_info->data.name;
1785                         break;
1786                 case MONO_PATCH_INFO_CLASS_INIT:
1787                         patch_id = patch_info->data.klass;
1788                         break;
1789                 case MONO_PATCH_INFO_WRAPPER:
1790                         hash = acfg->patch_to_plt_offset_wrapper [patch_info->data.method->wrapper_type];
1791                         if (!hash) {
1792                                 acfg->patch_to_plt_offset_wrapper [patch_info->data.method->wrapper_type] = g_hash_table_new (NULL, NULL);
1793                                 hash = acfg->patch_to_plt_offset_wrapper [patch_info->data.method->wrapper_type];
1794                         }
1795                         patch_id = patch_info->data.method;
1796                         break;
1797                 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1798                         /* Each addr should only occur once */
1799                         break;
1800                 default:
1801                         g_assert_not_reached ();
1802                 }
1803
1804                 if (patch_id) {
1805                         idx = GPOINTER_TO_UINT (g_hash_table_lookup (hash, patch_id));
1806                         if (idx)
1807                                 res = idx;
1808                         else
1809                                 g_hash_table_insert (hash, patch_id, GUINT_TO_POINTER (acfg->plt_offset));
1810                 }
1811
1812                 if (res == -1) {
1813                         res = acfg->plt_offset;
1814                         g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (acfg->plt_offset), new_ji);
1815                         acfg->plt_offset ++;
1816                 }
1817
1818                 /* Nullify the patch */
1819                 patch_info->type = MONO_PATCH_INFO_NONE;
1820
1821                 return res;
1822         }
1823         default:
1824                 return -1;
1825         }
1826 }
1827
1828 /**
1829  * get_got_offset:
1830  *
1831  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
1832  * JI could be found if it exists, otherwise allocates a new one.
1833  */
1834 static guint32
1835 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1836 {
1837         guint32 got_offset;
1838
1839         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
1840         if (got_offset)
1841                 return got_offset - 1;
1842
1843         got_offset = acfg->got_offset;
1844         acfg->got_offset ++;
1845
1846         acfg->stats.got_slots ++;
1847         acfg->stats.got_slot_types [ji->type] ++;
1848
1849         return got_offset;
1850 }
1851
1852 static guint32
1853 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1854 {
1855         MonoJumpInfo *copy;
1856         guint32 got_offset;
1857
1858         if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
1859                 got_offset = get_got_offset (acfg, ji);
1860                 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
1861                 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
1862                 g_ptr_array_add (acfg->shared_patches, copy);
1863         }
1864
1865         return get_got_offset (acfg, ji);
1866 }
1867
1868 /* Add a method to the list of methods which need to be emitted */
1869 static void
1870 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
1871 {
1872         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1873                 g_ptr_array_add (acfg->methods, method);
1874                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1875         }
1876 }
1877
1878 static guint32
1879 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1880 {
1881         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1882         
1883         g_assert (index);
1884
1885         return index - 1;
1886 }
1887
1888 static int
1889 add_method (MonoAotCompile *acfg, MonoMethod *method)
1890 {
1891         int index = acfg->method_index;
1892
1893         add_method_with_index (acfg, method, index);
1894
1895         /* FIXME: Fix quadratic behavior */
1896         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1897
1898         acfg->method_index ++;
1899
1900         return index;
1901 }
1902
1903 static void
1904 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1905 {
1906         MonoAotCompile *acfg = user_data;
1907         MonoJitICallInfo *callinfo = value;
1908         MonoMethod *wrapper;
1909         char *name;
1910
1911         if (!callinfo->sig)
1912                 return;
1913
1914         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1915         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1916         g_free (name);
1917
1918         add_method (acfg, wrapper);
1919 }
1920
1921 static MonoMethod*
1922 get_runtime_invoke_sig (MonoMethodSignature *sig)
1923 {
1924         MonoMethodBuilder *mb;
1925         MonoMethod *m;
1926
1927         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1928         m = mono_mb_create_method (mb, sig, 16);
1929         return mono_marshal_get_runtime_invoke (m);
1930 }
1931
1932 static MonoMethod*
1933 get_runtime_invoke (const char *signature)
1934 {
1935         return get_runtime_invoke_sig (mono_create_icall_signature (signature));
1936 }
1937
1938 static void
1939 add_wrappers (MonoAotCompile *acfg)
1940 {
1941         MonoMethod *m;
1942         int i, nallocators;
1943         MonoMethodSignature *csig;
1944
1945         /* 
1946          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1947          * so there is only one wrapper of a given type, or inlining their contents into their
1948          * callers.
1949          */
1950
1951         /* FIXME: Collect these automatically */
1952
1953         /* Runtime invoke wrappers */
1954
1955         /* void runtime-invoke () [.cctor] */
1956         add_method (acfg, get_runtime_invoke ("void"));
1957
1958         /* void runtime-invoke (string) [exception ctor] */
1959         add_method (acfg, get_runtime_invoke ("void string"));
1960
1961         /* void runtime-invoke (string, string) [exception ctor] */
1962         add_method (acfg, get_runtime_invoke ("void string string"));
1963
1964         /* string runtime-invoke () [Exception.ToString ()] */
1965         add_method (acfg, get_runtime_invoke ("string"));
1966
1967         /* void runtime-invoke (string, Exception) [exception ctor] */
1968         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1969         csig->hasthis = 1;
1970         csig->ret = &mono_defaults.void_class->byval_arg;
1971         csig->params [0] = &mono_defaults.string_class->byval_arg;
1972         csig->params [1] = &mono_defaults.exception_class->byval_arg;
1973         add_method (acfg, get_runtime_invoke_sig (csig));
1974
1975         /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1976         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1977         csig->hasthis = 1;
1978         csig->ret = &(mono_class_from_name (
1979                                                                                 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1980         csig->params [0] = &mono_defaults.string_class->byval_arg;
1981         csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1982         add_method (acfg, get_runtime_invoke_sig (csig));
1983
1984         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1985                 MonoMethod *method;
1986                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1987
1988                 method = mono_get_method (acfg->image, token, NULL);
1989
1990                 if (!strcmp (method->name, "Main"))
1991                         add_method (acfg, mono_marshal_get_runtime_invoke (method));
1992         }
1993
1994         /* JIT icall wrappers */
1995         /* FIXME: locking */
1996         g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1997
1998         /* Managed Allocators */
1999         nallocators = mono_gc_get_managed_allocator_types ();
2000         for (i = 0; i < nallocators; ++i) {
2001                 m = mono_gc_get_managed_allocator_by_type (i);
2002                 if (m)
2003                         add_method (acfg, m);
2004         }
2005
2006         /* stelemref */
2007         add_method (acfg, mono_marshal_get_stelemref ());
2008
2009         /* remoting-invoke wrappers */
2010         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2011                 MonoMethod *method;
2012                 MonoMethodSignature *sig;
2013                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2014
2015                 method = mono_get_method (acfg->image, token, NULL);
2016
2017                 sig = mono_method_signature (method);
2018
2019                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) && 
2020                         !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2021                         m = mono_marshal_get_remoting_invoke_with_check (method);
2022
2023                         add_method (acfg, m);
2024                 }
2025         }
2026 }
2027
2028 static void
2029 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2030 {
2031         int i, pindex, start_index, method_index;
2032         GPtrArray *patches;
2033         MonoJumpInfo *patch_info;
2034         MonoMethodHeader *header;
2035         gboolean skip;
2036         guint32 got_slot;
2037
2038         if (method) {
2039                 header = mono_method_get_header (method);
2040
2041                 method_index = get_method_index (acfg, method);
2042         }
2043
2044         /* Collect and sort relocations */
2045         patches = g_ptr_array_new ();
2046         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2047                 g_ptr_array_add (patches, patch_info);
2048         g_ptr_array_sort (patches, compare_patches);
2049
2050         start_index = 0;
2051         for (i = 0; i < code_len; i++) {
2052                 patch_info = NULL;
2053                 for (pindex = start_index; pindex < patches->len; ++pindex) {
2054                         patch_info = g_ptr_array_index (patches, pindex);
2055                         if (patch_info->ip.i >= i)
2056                                 break;
2057                 }
2058
2059 #ifdef MONO_ARCH_AOT_SUPPORTED
2060                 skip = FALSE;
2061                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2062                         start_index = pindex;
2063
2064                         switch (patch_info->type) {
2065                         case MONO_PATCH_INFO_NONE:
2066                                 break;
2067                         case MONO_PATCH_INFO_GOT_OFFSET: {
2068                                 guint32 offset = mono_arch_get_patch_offset (code + i);
2069                                 emit_bytes (acfg, code + i, offset);
2070                                 emit_symbol_diff (acfg, "got", ".", offset);
2071
2072                                 i += offset + 4 - 1;
2073                                 skip = TRUE;
2074                                 break;
2075                         }
2076                         default: {
2077                                 int plt_index;
2078                                 char *direct_call_target;
2079
2080                                 if (!is_got_patch (patch_info->type))
2081                                         break;
2082
2083                                 /*
2084                                  * If this patch is a call, try emitting a direct call instead of
2085                                  * through a PLT entry. This is possible if the called method is in
2086                                  * the same assembly and requires no initialization.
2087                                  */
2088                                 direct_call_target = NULL;
2089                                 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
2090                                         MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2091                                         if (callee_cfg) {
2092                                                 if (!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)) {
2093                                                         //printf ("DIRECT: %s %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (callee_cfg->method, TRUE));
2094                                                         direct_call_target = g_strdup_printf (".Lm_%x", get_method_index (acfg, callee_cfg->method));
2095                                                         patch_info->type = MONO_PATCH_INFO_NONE;
2096                                                         acfg->stats.direct_calls ++;
2097                                                 }
2098                                         }
2099
2100                                         acfg->stats.all_calls ++;
2101                                 }
2102
2103                                 if (!got_only && !direct_call_target) {
2104                                         plt_index = get_plt_index (acfg, patch_info);
2105                                         if (plt_index != -1) {
2106                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2107                                                 direct_call_target = g_strdup_printf (".Lp_%d", plt_index);
2108                                         }
2109                                 }
2110
2111                                 if (direct_call_target) {
2112 #if defined(__i386__) || defined(__x86_64__)
2113                                         g_assert (code [i] == 0xe8);
2114                                         /* Need to make sure this is exactly 5 bytes long */
2115                                         emit_byte (acfg, '\xe8');
2116                                         emit_symbol_diff (acfg, direct_call_target, ".", -4);
2117                                         i += 4;
2118 #elif defined(__arm__)
2119 #ifdef USE_BIN_WRITER
2120                                         /* FIXME: Can't encode this using the current symbol writer functions */
2121                                         g_assert_not_reached ();
2122 #else
2123                                         emit_unset_mode (acfg);
2124                                         fprintf (acfg->fp, "bl %s\n", direct_call_target);
2125                                         i += 4 - 1;
2126 #endif
2127 #endif
2128                                 } else {
2129                                         got_slot = get_got_offset (acfg, patch_info);
2130
2131                                         emit_bytes (acfg, code + i, mono_arch_get_patch_offset (code + i));
2132 #ifdef __x86_64__
2133                                         emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
2134 #elif defined(__i386__)
2135                                         emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
2136 #elif defined(__arm__)
2137                                         emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
2138 #else
2139                                         g_assert_not_reached ();
2140 #endif
2141                                         
2142                                         i += mono_arch_get_patch_offset (code + i) + 4 - 1;
2143                                 }
2144                                 skip = TRUE;
2145                         }
2146                         }
2147                 }
2148 #endif /* MONO_ARCH_AOT_SUPPORTED */
2149
2150                 if (!skip)
2151                         emit_bytes (acfg, code + i, 1);
2152         }
2153 }
2154
2155 static void
2156 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2157 {
2158         MonoMethod *method;
2159         int method_index;
2160         guint8 *code;
2161         char *symbol;
2162         int func_alignment = 16;
2163         MonoMethodHeader *header;
2164
2165         method = cfg->method;
2166         code = cfg->native_code;
2167         header = mono_method_get_header (method);
2168
2169         method_index = get_method_index (acfg, method);
2170
2171         /* Make the labels local */
2172         symbol = g_strdup_printf (".Lm_%x", method_index);
2173
2174         emit_alignment (acfg, func_alignment);
2175         emit_label (acfg, symbol);
2176         if (acfg->aot_opts.write_symbols)
2177                 emit_global (acfg, symbol, TRUE);
2178
2179         if (cfg->verbose_level > 0)
2180                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2181
2182         acfg->stats.code_size += cfg->code_len;
2183
2184         acfg->method_got_offsets [method_index] = acfg->got_offset;
2185
2186         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2187
2188         emit_line (acfg);
2189 }
2190
2191 /**
2192  * encode_patch:
2193  *
2194  *  Encode PATCH_INFO into its disk representation. If SHARED is true, encode some types
2195  * of patches by allocating a GOT entry for them, and encode the GOT offset instead.
2196  */
2197 static void
2198 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf, gboolean shared)
2199 {
2200         guint8 *p = buf;
2201
2202         switch (patch_info->type) {
2203         case MONO_PATCH_INFO_NONE:
2204                 break;
2205         case MONO_PATCH_INFO_IMAGE:
2206                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2207                 break;
2208         case MONO_PATCH_INFO_METHOD_REL:
2209                 encode_value ((gint)patch_info->data.offset, p, &p);
2210                 break;
2211         case MONO_PATCH_INFO_SWITCH: {
2212                 gpointer *table = (gpointer *)patch_info->data.table->table;
2213                 int k;
2214
2215                 encode_value (patch_info->data.table->table_size, p, &p);
2216                 for (k = 0; k < patch_info->data.table->table_size; k++)
2217                         encode_value ((int)(gssize)table [k], p, &p);
2218                 break;
2219         }
2220         case MONO_PATCH_INFO_METHODCONST:
2221         case MONO_PATCH_INFO_METHOD:
2222         case MONO_PATCH_INFO_METHOD_JUMP:
2223         case MONO_PATCH_INFO_ICALL_ADDR:
2224                 encode_method_ref (acfg, patch_info->data.method, p, &p);
2225                 break;
2226         case MONO_PATCH_INFO_INTERNAL_METHOD:
2227         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2228                 guint32 len = strlen (patch_info->data.name);
2229
2230                 encode_value (len, p, &p);
2231
2232                 memcpy (p, patch_info->data.name, len);
2233                 p += len;
2234                 *p++ = '\0';
2235                 break;
2236         }
2237         case MONO_PATCH_INFO_LDSTR: {
2238                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2239                 guint32 token = patch_info->data.token->token;
2240                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2241                 encode_value (image_index, p, &p);
2242                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2243                 break;
2244         }
2245         case MONO_PATCH_INFO_RVA:
2246         case MONO_PATCH_INFO_DECLSEC:
2247         case MONO_PATCH_INFO_LDTOKEN:
2248         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2249                 if (shared) {
2250                         guint32 offset = get_got_offset (acfg, patch_info);
2251                         encode_value (offset, p, &p);
2252                 } else {
2253                         encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2254                         encode_value (patch_info->data.token->token, p, &p);
2255                 }
2256                 break;
2257         case MONO_PATCH_INFO_EXC_NAME: {
2258                 MonoClass *ex_class;
2259
2260                 ex_class =
2261                         mono_class_from_name (mono_defaults.exception_class->image,
2262                                                                   "System", patch_info->data.target);
2263                 g_assert (ex_class);
2264                 encode_klass_ref (acfg, ex_class, p, &p);
2265                 break;
2266         }
2267         case MONO_PATCH_INFO_R4:
2268                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2269                 break;
2270         case MONO_PATCH_INFO_R8:
2271                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2272                 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2273                 break;
2274         case MONO_PATCH_INFO_VTABLE:
2275         case MONO_PATCH_INFO_CLASS:
2276         case MONO_PATCH_INFO_IID:
2277         case MONO_PATCH_INFO_ADJUSTED_IID:
2278                 if (shared) {
2279                         guint32 offset = get_got_offset (acfg, patch_info);
2280                         encode_value (offset, p, &p);
2281                 } else {
2282                         encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2283                 }
2284                 break;
2285         case MONO_PATCH_INFO_CLASS_INIT:
2286         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2287                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2288                 break;
2289         case MONO_PATCH_INFO_FIELD:
2290         case MONO_PATCH_INFO_SFLDA:
2291                 if (shared) {
2292                         guint32 offset = get_got_offset (acfg, patch_info);
2293                         encode_value (offset, p, &p);
2294                 } else {
2295                         encode_field_info (acfg, patch_info->data.field, p, &p);
2296                 }
2297                 break;
2298         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2299                 break;
2300         case MONO_PATCH_INFO_WRAPPER:
2301                 encode_value (patch_info->data.method->wrapper_type, p, &p);
2302
2303                 switch (patch_info->data.method->wrapper_type) {
2304                 case MONO_WRAPPER_REMOTING_INVOKE:
2305                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2306                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2307                         MonoMethod *m;
2308                         guint32 image_index;
2309                         guint32 token;
2310
2311                         m = mono_marshal_method_from_wrapper (patch_info->data.method);
2312                         image_index = get_image_index (acfg, m->klass->image);
2313                         token = m->token;
2314                         g_assert (image_index < 256);
2315                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2316
2317                         encode_value ((image_index << 24) + (mono_metadata_token_index (token)), p, &p);
2318                         break;
2319                 }
2320                 case MONO_WRAPPER_PROXY_ISINST:
2321                 case MONO_WRAPPER_LDFLD:
2322                 case MONO_WRAPPER_LDFLDA:
2323                 case MONO_WRAPPER_STFLD:
2324                 case MONO_WRAPPER_ISINST: {
2325                         MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (patch_info->data.method);
2326                         encode_klass_ref (acfg, proxy_class, p, &p);
2327                         break;
2328                 }
2329                 case MONO_WRAPPER_LDFLD_REMOTE:
2330                 case MONO_WRAPPER_STFLD_REMOTE:
2331                         break;
2332                 case MONO_WRAPPER_ALLOC: {
2333                         int alloc_type = mono_gc_get_managed_allocator_type (patch_info->data.method);
2334                         g_assert (alloc_type != -1);
2335                         encode_value (alloc_type, p, &p);
2336                         break;
2337                 }
2338                 case MONO_WRAPPER_STELEMREF:
2339                         break;
2340                 default:
2341                         g_assert_not_reached ();
2342                 }
2343                 break;
2344         default:
2345                 g_warning ("unable to handle jump info %d", patch_info->type);
2346                 g_assert_not_reached ();
2347         }
2348
2349         *endbuf = p;
2350 }
2351
2352 static void
2353 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2354 {
2355         guint8 *p = buf;
2356         guint32 last_offset, j, pindex;
2357         MonoJumpInfo *patch_info;
2358
2359         encode_value (n_patches, p, &p);
2360
2361         if (n_patches)
2362                 encode_value (first_got_offset, p, &p);
2363
2364         /* First encode the type+position table */
2365         last_offset = 0;
2366         j = 0;
2367         for (pindex = 0; pindex < patches->len; ++pindex) {
2368                 guint32 offset;
2369                 patch_info = g_ptr_array_index (patches, pindex);
2370                 
2371                 if (patch_info->type == MONO_PATCH_INFO_NONE)
2372                         /* Nothing to do */
2373                         continue;
2374
2375                 j ++;
2376                 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
2377                 offset = patch_info->ip.i - last_offset;
2378                 last_offset = patch_info->ip.i;
2379
2380                 /* Only the type is needed */
2381                 *p = patch_info->type;
2382                 p++;
2383         }
2384
2385         /* Then encode the other info */
2386         for (pindex = 0; pindex < patches->len; ++pindex) {
2387                 patch_info = g_ptr_array_index (patches, pindex);
2388
2389                 encode_patch (acfg, patch_info, p, &p, TRUE);
2390         }
2391
2392         *endbuf = p;
2393 }
2394
2395 static void
2396 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2397 {
2398         MonoMethod *method;
2399         GList *l;
2400         int pindex, buf_size, n_patches;
2401         guint8 *code;
2402         char *symbol;
2403         GPtrArray *patches;
2404         MonoJumpInfo *patch_info;
2405         MonoMethodHeader *header;
2406         guint32 method_index;
2407         guint8 *p, *buf;
2408         guint32 first_got_offset;
2409
2410         method = cfg->method;
2411         code = cfg->native_code;
2412         header = mono_method_get_header (method);
2413
2414         method_index = get_method_index (acfg, method);
2415
2416         /* Make the labels local */
2417         symbol = g_strdup_printf (".Lm_%x_p", method_index);
2418
2419         /* Sort relocations */
2420         patches = g_ptr_array_new ();
2421         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2422                 g_ptr_array_add (patches, patch_info);
2423         g_ptr_array_sort (patches, compare_patches);
2424
2425         first_got_offset = acfg->method_got_offsets [method_index];
2426
2427         /**********************/
2428         /* Encode method info */
2429         /**********************/
2430
2431         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2432         p = buf = g_malloc (buf_size);
2433
2434         if (mono_class_get_cctor (method->klass))
2435                 encode_klass_ref (acfg, method->klass, p, &p);
2436         else
2437                 /* Not needed when loading the method */
2438                 encode_value (0, p, &p);
2439
2440         /* String table */
2441         if (cfg->opt & MONO_OPT_SHARED) {
2442                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2443                 for (l = cfg->ldstr_list; l; l = l->next) {
2444                         encode_value ((long)l->data, p, &p);
2445                 }
2446         }
2447         else
2448                 /* Used only in shared mode */
2449                 g_assert (!cfg->ldstr_list);
2450
2451         n_patches = 0;
2452         for (pindex = 0; pindex < patches->len; ++pindex) {
2453                 patch_info = g_ptr_array_index (patches, pindex);
2454                 
2455                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2456                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
2457                         patch_info->type = MONO_PATCH_INFO_NONE;
2458                         /* Nothing to do */
2459                         continue;
2460                 }
2461
2462                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2463                         /* Stored in a GOT slot initialized at module load time */
2464                         patch_info->type = MONO_PATCH_INFO_NONE;
2465                         continue;
2466                 }
2467
2468                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) ||
2469                         (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) ||
2470                         (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) ||
2471                         (patch_info->type == MONO_PATCH_INFO_WRAPPER) ||
2472                         (patch_info->type == MONO_PATCH_INFO_CLASS_INIT)) {
2473                         /* Calls are made through the PLT */
2474                         patch_info->type = MONO_PATCH_INFO_NONE;
2475                         continue;
2476                 }
2477
2478                 n_patches ++;
2479         }
2480
2481         if (n_patches)
2482                 g_assert (cfg->has_got_slots);
2483
2484         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2485
2486         acfg->stats.info_size += p - buf;
2487
2488         /* Emit method info */
2489
2490         emit_label (acfg, symbol);
2491
2492         g_assert (p - buf < buf_size);
2493         emit_bytes (acfg, buf, p - buf);
2494         g_free (buf);
2495
2496         g_free (symbol);
2497 }
2498
2499 static void
2500 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2501 {
2502         MonoMethod *method;
2503         int k, buf_size, method_index;
2504         guint32 debug_info_size;
2505         guint8 *code;
2506         char *symbol;
2507         MonoMethodHeader *header;
2508         guint8 *p, *buf, *debug_info;
2509
2510         method = cfg->method;
2511         code = cfg->native_code;
2512         header = mono_method_get_header (method);
2513
2514         method_index = get_method_index (acfg, method);
2515
2516         /* Make the labels local */
2517         symbol = g_strdup_printf (".Le_%x_p", method_index);
2518
2519         mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2520
2521         buf_size = header->num_clauses * 256 + debug_info_size + 128;
2522         p = buf = g_malloc (buf_size);
2523
2524         encode_value (cfg->code_len, p, &p);
2525         encode_value (cfg->used_int_regs, p, &p);
2526
2527         /* Exception table */
2528         if (header->num_clauses) {
2529                 MonoJitInfo *jinfo = cfg->jit_info;
2530
2531                 for (k = 0; k < header->num_clauses; ++k) {
2532                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2533
2534                         encode_value (ei->exvar_offset, p, &p);
2535
2536                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2537                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2538
2539                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2540                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2541                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2542                 }
2543         }
2544
2545         g_assert (debug_info_size < buf_size);
2546
2547         encode_value (debug_info_size, p, &p);
2548         if (debug_info_size) {
2549                 memcpy (p, debug_info, debug_info_size);
2550                 p += debug_info_size;
2551                 g_free (debug_info);
2552         }
2553
2554         acfg->stats.ex_info_size += p - buf;
2555
2556         /* Emit info */
2557
2558         emit_label (acfg, symbol);
2559
2560         g_assert (p - buf < buf_size);
2561         emit_bytes (acfg, buf, p - buf);
2562         g_free (buf);
2563
2564         g_free (symbol);
2565 }
2566
2567 static void
2568 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2569 {
2570         MonoClass *klass = mono_class_get (acfg->image, token);
2571         guint8 *p, *buf;
2572         int i, buf_size;
2573         char *label;
2574         gboolean no_special_static, cant_encode;
2575
2576         buf_size = 10240 + (klass->vtable_size * 16);
2577         p = buf = g_malloc (buf_size);
2578
2579         g_assert (klass);
2580
2581         mono_class_init (klass);
2582
2583         mono_class_setup_vtable (klass);
2584
2585         /* 
2586          * Emit all the information which is required for creating vtables so
2587          * the runtime does not need to create the MonoMethod structures which
2588          * take up a lot of space.
2589          */
2590
2591         no_special_static = !mono_class_has_special_static_fields (klass);
2592
2593         /* Check whenever we have enough info to encode the vtable */
2594         cant_encode = FALSE;
2595         for (i = 0; i < klass->vtable_size; ++i) {
2596                 MonoMethod *cm = klass->vtable [i];
2597
2598                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
2599                         cant_encode = TRUE;
2600         }
2601
2602         if (klass->generic_container || cant_encode) {
2603                 encode_value (-1, p, &p);
2604         } else {
2605                 encode_value (klass->vtable_size, p, &p);
2606                 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);
2607                 if (klass->has_cctor)
2608                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2609                 if (klass->has_finalize)
2610                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2611  
2612                 encode_value (klass->instance_size, p, &p);
2613                 encode_value (mono_class_data_size (klass), p, &p);
2614                 encode_value (klass->packing_size, p, &p);
2615                 encode_value (klass->min_align, p, &p);
2616
2617                 for (i = 0; i < klass->vtable_size; ++i) {
2618                         MonoMethod *cm = klass->vtable [i];
2619
2620                         if (cm)
2621                                 encode_method_ref (acfg, cm, p, &p);
2622                         else
2623                                 encode_value (0, p, &p);
2624                 }
2625         }
2626
2627         acfg->stats.class_info_size += p - buf;
2628
2629         /* Emit the info */
2630         label = g_strdup_printf (".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2631         emit_label (acfg, label);
2632
2633         g_assert (p - buf < buf_size);
2634         emit_bytes (acfg, buf, p - buf);
2635         g_free (buf);
2636 }
2637
2638 /*
2639  * Calls made from AOTed code are routed through a table of jumps similar to the
2640  * ELF PLT (Program Linkage Table). The differences are the following:
2641  * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2642  *   GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2643  *   jumps. This means the jumps need to be patched when the address of the callee is
2644  *   known. Initially the PLT entries jump to code which transfers control to the
2645  *   AOT runtime through the first PLT entry.
2646  */
2647 static void
2648 emit_plt (MonoAotCompile *acfg)
2649 {
2650         char *symbol;
2651         int i, buf_size;
2652         guint8 *p, *buf;
2653         guint32 *plt_info_offsets;
2654
2655         /*
2656          * Encode info need to resolve PLT entries.
2657          */
2658         buf_size = acfg->plt_offset * 128;
2659         p = buf = g_malloc (buf_size);
2660
2661         plt_info_offsets = g_new0 (guint32, acfg->plt_offset);
2662
2663         for (i = 1; i < acfg->plt_offset; ++i) {
2664                 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
2665
2666                 plt_info_offsets [i] = p - buf;
2667                 encode_value (patch_info->type, p, &p);
2668                 encode_patch (acfg, patch_info, p, &p, FALSE);
2669         }
2670
2671         emit_line (acfg);
2672         symbol = g_strdup_printf ("plt");
2673
2674         /* This section will be made read-write by the AOT loader */
2675         emit_section_change (acfg, ".text", 0);
2676         emit_global (acfg, symbol, TRUE);
2677         emit_alignment (acfg, PAGESIZE);
2678         emit_label (acfg, symbol);
2679
2680 #if defined(USE_BIN_WRITER) && defined(__arm__)
2681         /* FIXME: */
2682         g_assert_not_reached ();
2683 #endif
2684
2685         /* 
2686          * The first plt entry is used to transfer code to the AOT loader. 
2687          */
2688         emit_label (acfg, ".Lp_0");
2689 #if defined(__i386__)
2690         /* It is filled up during loading by the AOT loader. */
2691         emit_zero_bytes (acfg, 16);
2692 #elif defined(__x86_64__)
2693         /* This should be exactly 16 bytes long */
2694         /* jmpq *<offset>(%rip) */
2695         emit_byte (acfg, '\xff');
2696         emit_byte (acfg, '\x25');
2697         emit_symbol_diff (acfg, "plt_jump_table", ".", -4);
2698         emit_zero_bytes (acfg, 10);
2699 #elif defined(__arm__)
2700         /* This is 8 bytes long, init_plt () depends on this */
2701         emit_unset_mode (acfg);
2702         fprintf (acfg->fp, "\tldr pc, [pc, #-4]\n");
2703         /* This is filled up during loading by the AOT loader */
2704         fprintf (acfg->fp, "\t.word 0\n");
2705 #else
2706         g_assert_not_reached ();
2707 #endif
2708
2709         for (i = 1; i < acfg->plt_offset; ++i) {
2710                 char *label;
2711
2712                 label = g_strdup_printf (".Lp_%d", i);
2713                 emit_label (acfg, label);
2714                 g_free (label);
2715 #if defined(__i386__)
2716                 /* Need to make sure this is 5 bytes long */
2717                 emit_byte (acfg, '\xe9');
2718                 label = g_strdup_printf (".Lpd_%d", i);
2719                 emit_symbol_diff (acfg, label, ".", -4);
2720                 g_free (label);
2721 #elif defined(__x86_64__)
2722                 /*
2723                  * We can't emit jumps because they are 32 bits only so they can't be patched.
2724                  * So we emit a jump table instead whose entries are patched by the AOT loader to
2725                  * point to .Lpd entries. ELF stores these in the GOT too, but we don't, since
2726                  * methods with GOT entries can't be called directly.
2727                  * We also emit the default PLT code here since the PLT code will not be patched.
2728                  * An x86_64 plt entry is 16 bytes long, init_plt () depends on this.
2729                  */
2730                 /* jmpq *<offset>(%rip) */
2731                 emit_byte (acfg, '\xff');
2732                 emit_byte (acfg, '\x25');
2733                 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)) -4);
2734                 /* mov <plt info offset>, %eax */
2735                 emit_byte (acfg, '\xb8');
2736                 emit_int32 (acfg, plt_info_offsets [i]);
2737                 /* jmp .Lp_0 */
2738                 emit_byte (acfg, '\xe9');
2739                 emit_symbol_diff (acfg, ".Lp_0", ".", -4);
2740 #elif defined(__arm__)
2741                 /* 
2742                  * Emit an indirect call since branch displacements are limited to 24 bits on 
2743                  * ARM. Put the jump table entries inline since offsets are even smaller on
2744                  * ARM.
2745                  * FIXME:
2746                  * - optimize OP_AOTCONST implementation
2747                  * - optimize the PLT entries
2748                  * - optimize SWITCH AOT implementation
2749                  * - implement IMT support
2750                  */
2751                 /* This is 8 bytes long, init_plt () depends on this */
2752                 emit_unset_mode (acfg);
2753                 fprintf (acfg->fp, "\tldr pc, [pc, #-4]\n");
2754                 /* This is filled up during loading by the AOT loader */
2755                 fprintf (acfg->fp, "\t.word 0\n");
2756 #else
2757                 g_assert_not_reached ();
2758 #endif
2759         }
2760
2761         symbol = g_strdup_printf ("plt_end");
2762         emit_global (acfg, symbol, TRUE);
2763         emit_label (acfg, symbol);
2764
2765         /* 
2766          * Emit the default targets for the PLT entries separately since these will not
2767          * be modified at runtime.
2768          */
2769         for (i = 1; i < acfg->plt_offset; ++i) {
2770                 char *label;
2771
2772                 label = g_strdup_printf (".Lpd_%d", i);
2773                 emit_label (acfg, label);
2774                 g_free (label);
2775
2776                 /* Put the offset into the register expected by mono_aot_plt_trampoline */
2777 #if defined(__i386__)
2778                 /* movl $const, %eax */
2779                 emit_byte (acfg, '\xb8');
2780                 emit_int32 (acfg, plt_info_offsets [i]);
2781                 /* jmp .Lp_0 */
2782                 emit_byte (acfg, '\xe9');
2783                 emit_symbol_diff (acfg, ".Lp_0", ".", -4);
2784 #elif defined(__x86_64__)
2785                 /* Emitted along with the PLT entries since they will not be patched */
2786 #elif defined(__arm__)
2787                 /* This is 12 bytes long, init_plt () depends on this */
2788                 emit_unset_mode (acfg);
2789                 fprintf (acfg->fp, "\tldr ip, [pc, #0]\n");
2790                 fprintf (acfg->fp, "\tb .Lp_0\n");
2791                 fprintf (acfg->fp, "\t.word %d\n", plt_info_offsets [i]);
2792 #else
2793                 g_assert_not_reached ();
2794 #endif
2795         }
2796
2797         /* Emit PLT info */
2798         symbol = g_strdup_printf ("plt_info");
2799         emit_global (acfg, symbol, FALSE);
2800         emit_label (acfg, symbol);
2801
2802         g_assert (p - buf < buf_size);
2803         emit_bytes (acfg, buf, p - buf);
2804         g_free (buf);
2805
2806         symbol = g_strdup_printf ("plt_jump_table_addr");
2807         emit_section_change (acfg, ".data", 0);
2808         emit_global (acfg, symbol, FALSE);
2809         emit_alignment (acfg, 8);
2810         emit_label (acfg, symbol);
2811         emit_pointer (acfg, "plt_jump_table");
2812
2813         symbol = g_strdup_printf ("plt_jump_table_size");
2814         emit_section_change (acfg, ".data", 0);
2815         emit_global (acfg, symbol, FALSE);
2816         emit_alignment (acfg, 8);
2817         emit_label (acfg, symbol);
2818         emit_symbol_diff (acfg, "plt_jump_table_end", "plt_jump_table", 0);
2819
2820         /* Don't make this a global so accesses don't need relocations */
2821         symbol = g_strdup_printf ("plt_jump_table");
2822         emit_section_change (acfg, ".bss", 0);
2823         emit_label (acfg, symbol);
2824
2825 #ifdef __x86_64__
2826         emit_zero_bytes (acfg, (int)(acfg->plt_offset * sizeof (gpointer)));
2827 #endif  
2828
2829         symbol = g_strdup_printf ("plt_jump_table_end");
2830         emit_label (acfg, symbol);
2831 }
2832
2833 static void
2834 emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code, 
2835                                  guint32 code_size, int got_offset, MonoJumpInfo *ji)
2836 {
2837         char *symbol;
2838         guint32 buf_size;
2839         MonoJumpInfo *patch_info;
2840         guint8 *buf, *p;
2841         GPtrArray *patches;
2842
2843         /* Emit code */
2844
2845         symbol = g_strdup_printf ("%s", name);
2846
2847         emit_section_change (acfg, ".text", 0);
2848         emit_global (acfg, symbol, TRUE);
2849         emit_label (acfg, symbol);
2850         g_free (symbol);
2851
2852         /* 
2853          * The code should access everything through the GOT, so we pass
2854          * TRUE here.
2855          */
2856         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
2857
2858         /* Emit info */
2859
2860         /* Sort relocations */
2861         patches = g_ptr_array_new ();
2862         for (patch_info = ji; patch_info; patch_info = patch_info->next)
2863                 g_ptr_array_add (patches, patch_info);
2864         g_ptr_array_sort (patches, compare_patches);
2865
2866         buf_size = patches->len * 128 + 128;
2867         buf = g_malloc (buf_size);
2868         p = buf;
2869
2870         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
2871         g_assert (p - buf < buf_size);
2872
2873         symbol = g_strdup_printf ("%s_p", name);
2874
2875         emit_section_change (acfg, ".text", 0);
2876         emit_global (acfg, symbol, TRUE);
2877         emit_label (acfg, symbol);
2878         g_free (symbol);
2879                 
2880         emit_bytes (acfg, buf, p - buf);
2881 }
2882
2883 /*
2884  * When running in aot-only mode, we can't create trampolines at runtime, so we create 
2885  * a few, and save them in the AOT file. Normal trampolines embed their argument as a 
2886  * literal inside the trampoline code, we can't do that here, so instead we embed an offset
2887  * which needs to be added to the trampoline address to get the address of the GOT slot
2888  * which contains the argument value.
2889  * The generated trampolines jump to the generic trampolines using another GOT slot, which
2890  * will be setup by the AOT loader to point to the generic trampoline code of the given 
2891  * type.
2892  * Currently, we only emit trampolines into the mscorlib AOT image.
2893  */
2894 static void
2895 emit_trampolines (MonoAotCompile *acfg)
2896 {
2897         char *symbol;
2898         int tramp_type, i, offset;
2899 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2900         guint32 code_size;
2901         MonoJumpInfo *ji;
2902         guint8 *code;
2903 #endif
2904
2905         if (!acfg->aot_opts.full_aot)
2906                 return;
2907         
2908         g_assert (acfg->image->assembly);
2909         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") != 0)
2910                 return;
2911
2912 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2913         /*
2914          * Emit the generic trampolines.
2915          *
2916          * We could save some code by treating the generic trampolines as a wrapper
2917          * method, but that approach has its own complexities, so we choose the simpler
2918          * method.
2919          */
2920         for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
2921                 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, TRUE);
2922
2923                 /* Emit trampoline code */
2924
2925                 symbol = g_strdup_printf ("generic_trampoline_%d", tramp_type);
2926
2927                 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
2928
2929                 g_free (symbol);
2930         }
2931
2932         code = mono_arch_get_nullified_class_init_trampoline (&code_size);
2933         emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL);
2934
2935         /* Emit the exception related code pieces */
2936         code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
2937         emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji);
2938     code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
2939         emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji);
2940         code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
2941         emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji);
2942         code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
2943         emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji);
2944         code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
2945         emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji);
2946         code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
2947         emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji);
2948 #endif
2949
2950         /*
2951          * FIXME: Maybe we should use more specific trampolines (i.e. one class init for each
2952          * class).
2953          */
2954
2955         /* Reserve some entries at the end of the GOT for our use */
2956         acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
2957
2958         symbol = g_strdup_printf ("trampolines");
2959
2960         emit_section_change (acfg, ".text", 0);
2961         emit_global (acfg, symbol, TRUE);
2962         emit_label (acfg, symbol);
2963
2964         for (i = 0; i < acfg->num_aot_trampolines; ++i) {
2965                 offset = acfg->got_offset + (i * 2);
2966
2967 #if defined(__x86_64__)
2968                 /* This should be exactly 16 bytes long */
2969                 /* It should work together with the generic trampoline code in tramp-amd64.c */
2970                 /* call *<offset>(%rip) */
2971                 emit_byte (acfg, '\x41');
2972                 emit_byte (acfg, '\xff');
2973                 emit_byte (acfg, '\x15');
2974                 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
2975                 /* This should be relative to the start of the trampoline */
2976                 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
2977                 emit_zero_bytes (acfg, 5);
2978 #else
2979                 g_assert_not_reached ();
2980 #endif
2981         }
2982
2983         symbol = g_strdup_printf ("trampolines_info");
2984
2985         emit_section_change (acfg, ".text", 0);
2986         emit_global (acfg, symbol, TRUE);
2987         emit_alignment (acfg, PAGESIZE);
2988         emit_label (acfg, symbol);
2989
2990         emit_int32 (acfg, acfg->num_aot_trampolines);
2991         emit_int32 (acfg, acfg->got_offset);
2992 }
2993
2994 static gboolean
2995 str_begins_with (const char *str1, const char *str2)
2996 {
2997         int len = strlen (str2);
2998         return strncmp (str1, str2, len) == 0;
2999 }
3000
3001 static void
3002 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3003 {
3004         gchar **args, **ptr;
3005
3006         memset (opts, 0, sizeof (*opts));
3007
3008         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3009         for (ptr = args; ptr && *ptr; ptr ++) {
3010                 const char *arg = *ptr;
3011
3012                 if (str_begins_with (arg, "outfile=")) {
3013                         opts->outfile = g_strdup (arg + strlen ("outfile="));
3014                 } else if (str_begins_with (arg, "save-temps")) {
3015                         opts->save_temps = TRUE;
3016                 } else if (str_begins_with (arg, "keep-temps")) {
3017                         opts->save_temps = TRUE;
3018                 } else if (str_begins_with (arg, "write-symbols")) {
3019                         opts->write_symbols = TRUE;
3020                 } else if (str_begins_with (arg, "metadata-only")) {
3021                         opts->metadata_only = TRUE;
3022                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3023                         opts->bind_to_runtime_version = TRUE;
3024                 } else if (str_begins_with (arg, "full")) {
3025                         opts->full_aot = TRUE;
3026                 } else {
3027                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3028                         exit (1);
3029                 }
3030         }
3031 }
3032
3033 static void
3034 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3035 {
3036         MonoMethod *method = (MonoMethod*)key;
3037         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3038         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3039         MonoAotCompile *acfg = user_data;
3040
3041         new_ji->image = ji->image;
3042         new_ji->token = ji->token;
3043         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3044 }
3045
3046 static void
3047 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3048 {
3049         MonoCompile *cfg;
3050         MonoJumpInfo *patch_info;
3051         gboolean skip;
3052         int index;
3053
3054         if (acfg->aot_opts.metadata_only)
3055                 return;
3056
3057         index = get_method_index (acfg, method);
3058
3059         /* fixme: maybe we can also precompile wrapper methods */
3060         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3061                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3062                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3063                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3064                 return;
3065         }
3066
3067         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3068                 return;
3069
3070         acfg->stats.mcount++;
3071
3072         if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3073                 /* 
3074                  * FIXME: Enabling this causes virtual-sync.exe to fail, since the trampoline
3075                  * code can't determine that it needs to insert a sync wrapper in the AOT case.
3076                  */
3077                 return;
3078         }
3079
3080         //acfg->opts &= ~MONO_OPT_GSHARED;
3081
3082         if (!(acfg->opts & MONO_OPT_GSHARED)) {
3083                 if (method->is_generic || method->klass->generic_container) {
3084                         acfg->stats.genericcount ++;
3085                         return;
3086                 }
3087         }
3088
3089         /*
3090          * Since these methods are the only ones which are compiled with
3091          * AOT support, and they are not used by runtime startup/shutdown code,
3092          * the runtime will not see AOT methods during AOT compilation,so it
3093          * does not need to support them by creating a fake GOT etc.
3094          */
3095         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3096         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3097                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3098                 acfg->stats.genericcount ++;
3099                 return;
3100         }
3101         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3102                 /* Let the exception happen at runtime */
3103                 return;
3104         }
3105
3106         if (cfg->disable_aot) {
3107                 //printf ("Skip (other): %s\n", mono_method_full_name (method, TRUE));
3108                 acfg->stats.ocount++;
3109                 mono_destroy_compile (cfg);
3110                 return;
3111         }
3112
3113         /* Nullify patches which need no aot processing */
3114         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3115                 switch (patch_info->type) {
3116                 case MONO_PATCH_INFO_LABEL:
3117                 case MONO_PATCH_INFO_BB:
3118                         patch_info->type = MONO_PATCH_INFO_NONE;
3119                         break;
3120                 default:
3121                         break;
3122                 }
3123         }
3124
3125         /* Collect method->token associations from the cfg */
3126         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3127
3128         skip = FALSE;
3129         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3130                 switch (patch_info->type) {
3131                 case MONO_PATCH_INFO_ABS:
3132                         /* unable to handle this */
3133                         //printf ("Skip (abs addr):   %s %d\n", mono_method_full_name (method, TRUE), patch_info->type);
3134                         skip = TRUE;    
3135                         break;
3136                 default:
3137                         break;
3138                 }
3139         }
3140
3141         if (skip) {
3142                 acfg->stats.abscount++;
3143                 mono_destroy_compile (cfg);
3144                 return;
3145         }
3146
3147         skip = FALSE;
3148         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3149                 if (patch_info->type == MONO_PATCH_INFO_METHOD_JUMP) {
3150                         /* 
3151                          * FIXME: We can't handle this because mono_jit_compile_method_inner will try
3152                          * to patch the AOT code when the target of the jump is compiled.
3153                          */
3154                         skip = TRUE;
3155                         break;
3156                 }
3157         }
3158
3159         if (skip) {
3160                 acfg->stats.ocount++;
3161                 mono_destroy_compile (cfg);
3162                 return;
3163         }
3164
3165         /* some wrappers are very common */
3166         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3167                 if (patch_info->type == MONO_PATCH_INFO_METHODCONST) {
3168                         switch (patch_info->data.method->wrapper_type) {
3169                         case MONO_WRAPPER_PROXY_ISINST:
3170                                 patch_info->type = MONO_PATCH_INFO_WRAPPER;
3171                         }
3172                 }
3173
3174                 if (patch_info->type == MONO_PATCH_INFO_METHOD) {
3175                         switch (patch_info->data.method->wrapper_type) {
3176                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3177                         case MONO_WRAPPER_XDOMAIN_INVOKE:
3178                         case MONO_WRAPPER_STFLD:
3179                         case MONO_WRAPPER_LDFLD:
3180                         case MONO_WRAPPER_LDFLDA:
3181                         case MONO_WRAPPER_LDFLD_REMOTE:
3182                         case MONO_WRAPPER_STFLD_REMOTE:
3183                         case MONO_WRAPPER_STELEMREF:
3184                         case MONO_WRAPPER_ISINST:
3185                         case MONO_WRAPPER_PROXY_ISINST:
3186                         case MONO_WRAPPER_ALLOC:
3187                         case MONO_WRAPPER_REMOTING_INVOKE:
3188                                 patch_info->type = MONO_PATCH_INFO_WRAPPER;
3189                                 break;
3190                         }
3191                 }
3192         }
3193
3194         skip = FALSE;
3195         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3196                 switch (patch_info->type) {
3197                 case MONO_PATCH_INFO_METHOD:
3198                 case MONO_PATCH_INFO_METHODCONST:
3199                         if (patch_info->data.method->wrapper_type) {
3200                                 /* unable to handle this */
3201                                 //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));
3202                                 skip = TRUE;
3203                                 break;
3204                         }
3205                         if (!patch_info->data.method->token) {
3206                                 /* The method is part of a constructed type like Int[,].Set (). */
3207                                 if (!g_hash_table_lookup (acfg->token_info_hash, patch_info->data.method))
3208                                         skip = TRUE;
3209                         }
3210                         if (patch_info->data.method->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, patch_info->data.method))
3211                                 /* FIXME: Can't encode these */
3212                                 skip = TRUE;
3213                         break;
3214                 case MONO_PATCH_INFO_VTABLE:
3215                 case MONO_PATCH_INFO_CLASS_INIT:
3216                 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3217                 case MONO_PATCH_INFO_CLASS:
3218                 case MONO_PATCH_INFO_IID:
3219                 case MONO_PATCH_INFO_ADJUSTED_IID:
3220                         if (!patch_info->data.klass->type_token)
3221                                 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))
3222                                         skip = TRUE;
3223                         break;
3224                 default:
3225                         break;
3226                 }
3227         }
3228
3229         if (skip) {
3230                 acfg->stats.wrappercount++;
3231                 mono_destroy_compile (cfg);
3232                 return;
3233         }
3234
3235         /* Determine whenever the method has GOT slots */
3236         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3237                 switch (patch_info->type) {
3238                 case MONO_PATCH_INFO_GOT_OFFSET:
3239                 case MONO_PATCH_INFO_NONE:
3240                 case MONO_PATCH_INFO_METHOD:
3241                 case MONO_PATCH_INFO_INTERNAL_METHOD:
3242                 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3243                 case MONO_PATCH_INFO_WRAPPER:
3244                         break;
3245                 case MONO_PATCH_INFO_IMAGE:
3246                         if (patch_info->data.image == acfg->image)
3247                                 /* Stored in GOT slot 0 */
3248                                 break;
3249                         /* Fall through */
3250                 default:
3251                         cfg->has_got_slots = TRUE;
3252                         break;
3253                 }
3254         }
3255
3256         if (!cfg->has_got_slots)
3257                 acfg->stats.methods_without_got_slots ++;
3258
3259         /* Make a copy of the patch info which is in the mempool */
3260         {
3261                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3262
3263                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3264                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3265
3266                         if (!patches)
3267                                 patches = new_patch_info;
3268                         else
3269                                 patches_end->next = new_patch_info;
3270                         patches_end = new_patch_info;
3271                 }
3272                 cfg->patch_info = patches;
3273         }
3274
3275         /* Free some fields used by cfg to conserve memory */
3276         mono_mempool_destroy (cfg->mempool);
3277         cfg->mempool = NULL;
3278         g_free (cfg->varinfo);
3279         cfg->varinfo = NULL;
3280         g_free (cfg->vars);
3281         cfg->vars = NULL;
3282         if (cfg->rs) {
3283                 mono_regstate_free (cfg->rs);
3284                 cfg->rs = NULL;
3285         }
3286
3287         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
3288
3289         acfg->cfgs [index] = cfg;
3290
3291         g_hash_table_insert (acfg->method_to_cfg, cfg->method, cfg);
3292
3293         acfg->stats.ccount++;
3294 }
3295
3296 static void
3297 load_profile_files (MonoAotCompile *acfg)
3298 {
3299         FILE *infile;
3300         char *tmp;
3301         int file_index, res, method_index, i;
3302         char ver [256];
3303         guint32 token;
3304         GList *unordered;
3305
3306         file_index = 0;
3307         while (TRUE) {
3308                 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);
3309
3310                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR))
3311                         break;
3312
3313                 infile = fopen (tmp, "r");
3314                 g_assert (infile);
3315
3316                 printf ("Using profile data file '%s'\n", tmp);
3317
3318                 file_index ++;
3319
3320                 res = fscanf (infile, "%32s\n", ver);
3321                 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3322                         printf ("Profile file has wrong version or invalid.\n");
3323                         fclose (infile);
3324                         continue;
3325                 }
3326
3327                 while (TRUE) {
3328                         res = fscanf (infile, "%d\n", &token);
3329                         if (res < 1)
3330                                 break;
3331
3332                         method_index = mono_metadata_token_index (token) - 1;
3333
3334                         if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3335                                 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3336                 }
3337                 fclose (infile);
3338         }
3339
3340         /* Add missing methods */
3341         unordered = NULL;
3342         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3343                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3344                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3345         }
3346         unordered = g_list_reverse (unordered);
3347         if (acfg->method_order)
3348                 g_list_last (acfg->method_order)->next = unordered;
3349         else
3350                 acfg->method_order = unordered;
3351 }
3352
3353 /**
3354  * alloc_got_slots:
3355  *
3356  *  Collect all patches which have shared GOT entries and alloc entries for them. The
3357  * rest will get entries allocated during emit_code ().
3358  */
3359 static void
3360 alloc_got_slots (MonoAotCompile *acfg)
3361 {
3362         int i;
3363         GList *l;
3364         MonoJumpInfo *ji;
3365
3366         /* Slot 0 is reserved for the address of the current assembly */
3367         ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3368         ji->type = MONO_PATCH_INFO_IMAGE;
3369         ji->data.image = acfg->image;
3370
3371         get_shared_got_offset (acfg, ji);
3372
3373         for (l = acfg->method_order; l != NULL; l = l->next) {
3374                 i = GPOINTER_TO_UINT (l->data);
3375
3376                 if (acfg->cfgs [i]) {
3377                         MonoCompile *cfg = acfg->cfgs [i];
3378
3379                         for (ji = cfg->patch_info; ji; ji = ji->next) {
3380                                 switch (ji->type) {
3381                                 case MONO_PATCH_INFO_VTABLE:
3382                                 case MONO_PATCH_INFO_CLASS:
3383                                 case MONO_PATCH_INFO_IID:
3384                                 case MONO_PATCH_INFO_ADJUSTED_IID:
3385                                 case MONO_PATCH_INFO_FIELD:
3386                                 case MONO_PATCH_INFO_SFLDA:
3387                                 case MONO_PATCH_INFO_DECLSEC:
3388                                 case MONO_PATCH_INFO_LDTOKEN:
3389                                 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3390                                 case MONO_PATCH_INFO_RVA:
3391                                         get_shared_got_offset (acfg, ji);
3392                                         break;
3393                                 default:
3394                                         break;
3395                                 }
3396                         }
3397                 }
3398         }
3399 }
3400
3401 static void
3402 emit_code (MonoAotCompile *acfg)
3403 {
3404         int i;
3405         char *symbol;
3406         GList *l;
3407
3408         symbol = g_strdup_printf ("methods");
3409         emit_section_change (acfg, ".text", 0);
3410         emit_global (acfg, symbol, TRUE);
3411         emit_alignment (acfg, 8);
3412         emit_label (acfg, symbol);
3413
3414         for (l = acfg->method_order; l != NULL; l = l->next) {
3415                 i = GPOINTER_TO_UINT (l->data);
3416
3417                 if (acfg->cfgs [i])
3418                         emit_method_code (acfg, acfg->cfgs [i]);
3419         }
3420
3421         symbol = g_strdup_printf ("methods_end");
3422         emit_section_change (acfg, ".text", 0);
3423         emit_global (acfg, symbol, FALSE);
3424         emit_alignment (acfg, 8);
3425         emit_label (acfg, symbol);
3426
3427         symbol = g_strdup_printf ("method_offsets");
3428         emit_section_change (acfg, ".text", 1);
3429         emit_global (acfg, symbol, FALSE);
3430         emit_alignment (acfg, 8);
3431         emit_label (acfg, symbol);
3432
3433         for (i = 0; i < acfg->nmethods; ++i) {
3434                 if (acfg->cfgs [i]) {
3435                         symbol = g_strdup_printf (".Lm_%x", i);
3436                         emit_symbol_diff (acfg, symbol, "methods", 0);
3437                 } else {
3438                         emit_int32 (acfg, 0xffffffff);
3439                 }
3440         }
3441         emit_line (acfg);
3442 }
3443
3444 static void
3445 emit_info (MonoAotCompile *acfg)
3446 {
3447         int i;
3448         char *symbol;
3449         GList *l;
3450
3451         /* Emit method info */
3452         symbol = g_strdup_printf ("method_info");
3453         emit_section_change (acfg, ".text", 1);
3454         emit_global (acfg, symbol, FALSE);
3455         emit_alignment (acfg, 8);
3456         emit_label (acfg, symbol);
3457
3458         /* To reduce size of generated assembly code */
3459         symbol = g_strdup_printf ("mi");
3460         emit_label (acfg, symbol);
3461
3462         for (l = acfg->method_order; l != NULL; l = l->next) {
3463                 i = GPOINTER_TO_UINT (l->data);
3464
3465                 if (acfg->cfgs [i])
3466                         emit_method_info (acfg, acfg->cfgs [i]);
3467         }
3468
3469         symbol = g_strdup_printf ("method_info_offsets");
3470         emit_section_change (acfg, ".text", 1);
3471         emit_global (acfg, symbol, FALSE);
3472         emit_alignment (acfg, 8);
3473         emit_label (acfg, symbol);
3474
3475         for (i = 0; i < acfg->nmethods; ++i) {
3476                 if (acfg->cfgs [i]) {
3477                         symbol = g_strdup_printf (".Lm_%x_p", i);
3478                         emit_symbol_diff (acfg, symbol, "mi", 0);
3479                 } else {
3480                         emit_int32 (acfg, 0);
3481                 }
3482         }
3483         emit_line (acfg);
3484 }
3485
3486 static void
3487 emit_wrapper_info (MonoAotCompile *acfg)
3488 {
3489         int i, index;
3490         char *symbol;
3491         char *name;
3492
3493         /* Emit method info */
3494         symbol = g_strdup_printf ("wrapper_info");
3495         emit_section_change (acfg, ".text", 1);
3496         emit_global (acfg, symbol, FALSE);
3497         emit_alignment (acfg, 8);
3498         emit_label (acfg, symbol);
3499
3500         if (!acfg->aot_opts.full_aot)
3501                 return;
3502
3503         for (i = 0; i < acfg->nmethods; ++i) {
3504                 MonoCompile *cfg = acfg->cfgs [i];
3505
3506                 if (!cfg || !cfg->method->wrapper_type)
3507                         continue;
3508
3509                 index = get_method_index (acfg, cfg->method);
3510
3511                 // FIXME: Optimize disk usage and lookup speed
3512                 name = mono_method_full_name (cfg->method, TRUE);
3513                 emit_string (acfg, name);
3514                 emit_alignment (acfg, 4);
3515                 emit_int32 (acfg, index);
3516         }
3517
3518         emit_byte (acfg, 0);
3519
3520         emit_line (acfg);
3521 }       
3522
3523 static void
3524 emit_method_order (MonoAotCompile *acfg)
3525 {
3526         int i, index, len;
3527         char *symbol;
3528         GList *l;
3529
3530         symbol = g_strdup_printf ("method_order");
3531         emit_section_change (acfg, ".text", 1);
3532         emit_global (acfg, symbol, FALSE);
3533         emit_alignment (acfg, 8);
3534         emit_label (acfg, symbol);
3535
3536         /* First emit an index table */
3537         index = 0;
3538         len = 0;
3539         for (l = acfg->method_order; l != NULL; l = l->next) {
3540                 i = GPOINTER_TO_UINT (l->data);
3541
3542                 if (acfg->cfgs [i]) {
3543                         if ((index % 1024) == 0) {
3544                                 emit_int32 (acfg, i);
3545                         }
3546
3547                         index ++;
3548                 }
3549
3550                 len ++;
3551         }
3552         emit_int32 (acfg, 0xffffff);
3553
3554         /* Then emit the whole method order */
3555         for (l = acfg->method_order; l != NULL; l = l->next) {
3556                 i = GPOINTER_TO_UINT (l->data);
3557
3558                 if (acfg->cfgs [i]) {
3559                         emit_int32 (acfg, i);
3560                 }
3561         }       
3562         emit_line (acfg);
3563
3564         symbol = g_strdup_printf ("method_order_end");
3565         emit_section_change (acfg, ".text", 1);
3566         emit_global (acfg, symbol, FALSE);
3567         emit_label (acfg, symbol);
3568 }
3569
3570 static void
3571 emit_exception_info (MonoAotCompile *acfg)
3572 {
3573         int i;
3574         char *symbol;
3575
3576         symbol = g_strdup_printf ("ex_info");
3577         emit_section_change (acfg, ".text", 1);
3578         emit_global (acfg, symbol, FALSE);
3579         emit_alignment (acfg, 8);
3580         emit_label (acfg, symbol);
3581
3582         /* To reduce size of generated assembly */
3583         symbol = g_strdup_printf ("ex");
3584         emit_label (acfg, symbol);
3585
3586         for (i = 0; i < acfg->nmethods; ++i) {
3587                 if (acfg->cfgs [i])
3588                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
3589         }
3590
3591         symbol = g_strdup_printf ("ex_info_offsets");
3592         emit_section_change (acfg, ".text", 1);
3593         emit_global (acfg, symbol, FALSE);
3594         emit_alignment (acfg, 8);
3595         emit_label (acfg, symbol);
3596
3597         for (i = 0; i < acfg->nmethods; ++i) {
3598                 if (acfg->cfgs [i]) {
3599                         symbol = g_strdup_printf (".Le_%x_p", i);
3600                         emit_symbol_diff (acfg, symbol, "ex", 0);
3601                 } else {
3602                         emit_int32 (acfg, 0);
3603                 }
3604         }
3605         emit_line (acfg);
3606 }
3607
3608 static void
3609 emit_class_info (MonoAotCompile *acfg)
3610 {
3611         int i;
3612         char *symbol;
3613
3614         symbol = g_strdup_printf ("class_info");
3615         emit_section_change (acfg, ".text", 1);
3616         emit_global (acfg, symbol, FALSE);
3617         emit_alignment (acfg, 8);
3618         emit_label (acfg, symbol);
3619
3620         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
3621                 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
3622
3623         symbol = g_strdup_printf ("class_info_offsets");
3624         emit_section_change (acfg, ".text", 1);
3625         emit_global (acfg, symbol, FALSE);
3626         emit_alignment (acfg, 8);
3627         emit_label (acfg, symbol);
3628
3629         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3630                 symbol = g_strdup_printf (".LK_I_%x", i);
3631                 emit_symbol_diff (acfg, symbol, "class_info", 0);
3632         }
3633         emit_line (acfg);
3634 }
3635
3636 typedef struct ClassNameTableEntry {
3637         guint32 token, index;
3638         struct ClassNameTableEntry *next;
3639 } ClassNameTableEntry;
3640
3641 static void
3642 emit_class_name_table (MonoAotCompile *acfg)
3643 {
3644         int i, table_size;
3645         guint32 token, hash;
3646         MonoClass *klass;
3647         GPtrArray *table;
3648         char *full_name;
3649         char *symbol;
3650         ClassNameTableEntry *entry, *new_entry;
3651
3652         /*
3653          * Construct a chained hash table for mapping class names to typedef tokens.
3654          */
3655         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
3656         table = g_ptr_array_sized_new (table_size);
3657         for (i = 0; i < table_size; ++i)
3658                 g_ptr_array_add (table, NULL);
3659         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3660                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3661                 klass = mono_class_get (acfg->image, token);
3662                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
3663                 hash = g_str_hash (full_name) % table_size;
3664                 g_free (full_name);
3665
3666                 /* FIXME: Allocate from the mempool */
3667                 new_entry = g_new0 (ClassNameTableEntry, 1);
3668                 new_entry->token = token;
3669
3670                 entry = g_ptr_array_index (table, hash);
3671                 if (entry == NULL) {
3672                         new_entry->index = hash;
3673                         g_ptr_array_index (table, hash) = new_entry;
3674                 } else {
3675                         while (entry->next)
3676                                 entry = entry->next;
3677                         
3678                         entry->next = new_entry;
3679                         new_entry->index = table->len;
3680                         g_ptr_array_add (table, new_entry);
3681                 }
3682         }
3683
3684         /* Emit the table */
3685         symbol = g_strdup_printf ("class_name_table");
3686         emit_section_change (acfg, ".text", 0);
3687         emit_global (acfg, symbol, FALSE);
3688         emit_alignment (acfg, 8);
3689         emit_label (acfg, symbol);
3690
3691         /* FIXME: Optimize memory usage */
3692         g_assert (table_size < 65000);
3693         emit_int16 (acfg, table_size);
3694         g_assert (table->len < 65000);
3695         for (i = 0; i < table->len; ++i) {
3696                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
3697
3698                 if (entry == NULL) {
3699                         emit_int16 (acfg, 0);
3700                         emit_int16 (acfg, 0);
3701                 } else {
3702                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
3703                         if (entry->next)
3704                                 emit_int16 (acfg, entry->next->index);
3705                         else
3706                                 emit_int16 (acfg, 0);
3707                 }
3708         }
3709 }
3710
3711 static void
3712 emit_image_table (MonoAotCompile *acfg)
3713 {
3714         int i;
3715         char *symbol;
3716
3717         /*
3718          * The image table is small but referenced in a lot of places.
3719          * So we emit it at once, and reference its elements by an index.
3720          */
3721
3722         symbol = g_strdup_printf ("mono_image_table");
3723         emit_section_change (acfg, ".text", 1);
3724         emit_global (acfg, symbol, FALSE);
3725         emit_alignment (acfg, 8);
3726         emit_label (acfg, symbol);
3727         emit_int32 (acfg, acfg->image_table->len);
3728         for (i = 0; i < acfg->image_table->len; i++) {
3729                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
3730                 MonoAssemblyName *aname = &image->assembly->aname;
3731
3732                 /* FIXME: Support multi-module assemblies */
3733                 g_assert (image->assembly->image == image);
3734
3735                 emit_string (acfg, image->assembly_name);
3736                 emit_string (acfg, image->guid);
3737                 emit_string (acfg, aname->culture ? aname->culture : "");
3738                 emit_string (acfg, (const char*)aname->public_key_token);
3739
3740                 emit_alignment (acfg, 8);
3741                 emit_int32 (acfg, aname->flags);
3742                 emit_int32 (acfg, aname->major);
3743                 emit_int32 (acfg, aname->minor);
3744                 emit_int32 (acfg, aname->build);
3745                 emit_int32 (acfg, aname->revision);
3746         }
3747 }
3748
3749 static void
3750 emit_got_info (MonoAotCompile *acfg)
3751 {
3752         char *symbol;
3753         int i, buf_size;
3754         guint8 *p, *buf;
3755         guint32 *got_info_offsets;
3756
3757         /**
3758          * FIXME: 
3759          * - optimize offsets table.
3760          * - reduce number of exported symbols.
3761          * - emit info for a klass only once.
3762          * - determine when a method uses a GOT slot which is guaranteed to be already 
3763          *   initialized.
3764          * - clean up and document the code.
3765          * - use String.Empty in class libs.
3766          */
3767
3768         /* Encode info required to decode shared GOT entries */
3769         buf_size = acfg->shared_patches->len * 64;
3770         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
3771         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
3772         for (i = 0; i < acfg->shared_patches->len; ++i) {
3773                 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
3774
3775                 /* No need to encode the patch type */
3776                 got_info_offsets [i] = p - buf;
3777                 encode_patch (acfg, ji, p, &p, FALSE);
3778         }
3779
3780         g_assert (p - buf <= buf_size);
3781
3782         acfg->stats.got_info_size = p - buf;
3783
3784         /* Emit got_info table */
3785         symbol = g_strdup_printf ("got_info");
3786         emit_section_change (acfg, ".text", 1);
3787         emit_global (acfg, symbol, FALSE);
3788         emit_alignment (acfg, 8);
3789         emit_label (acfg, symbol);
3790
3791         emit_bytes (acfg, buf, p - buf);
3792
3793         /* Emit got_info_offsets table */
3794         symbol = g_strdup_printf ("got_info_offsets");
3795         emit_section_change (acfg, ".text", 1);
3796         emit_global (acfg, symbol, FALSE);
3797         emit_alignment (acfg, 8);
3798         emit_label (acfg, symbol);
3799
3800         for (i = 0; i < acfg->shared_patches->len; ++i)
3801                 emit_int32 (acfg, got_info_offsets [i]);
3802
3803         acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
3804 }
3805
3806 static void
3807 emit_got (MonoAotCompile *acfg)
3808 {
3809         char *symbol;
3810
3811         /* Don't make GOT global so accesses to it don't need relocations */
3812         symbol = g_strdup_printf ("got");
3813         emit_section_change (acfg, ".bss", 1);
3814         emit_alignment (acfg, 8);
3815         emit_label (acfg, symbol);
3816         if ((acfg->got_offset + acfg->num_trampoline_got_entries) > 0)
3817                 emit_zero_bytes (acfg, (int)((acfg->got_offset + acfg->num_trampoline_got_entries) * sizeof (gpointer)));
3818
3819         symbol = g_strdup_printf ("got_addr");
3820         emit_section_change (acfg, ".data", 1);
3821         emit_global (acfg, symbol, FALSE);
3822         emit_alignment (acfg, 8);
3823         emit_label (acfg, symbol);
3824         emit_pointer (acfg, "got");
3825
3826         symbol = g_strdup_printf ("got_size");
3827         emit_section_change (acfg, ".data", 1);
3828         emit_global (acfg, symbol, FALSE);
3829         emit_alignment (acfg, 8);
3830         emit_label (acfg, symbol);
3831         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
3832 }
3833
3834 static void
3835 emit_globals (MonoAotCompile *acfg)
3836 {
3837         char *opts_str;
3838
3839         emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
3840
3841         emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
3842
3843         opts_str = g_strdup_printf ("%d", acfg->opts);
3844         emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
3845         g_free (opts_str);
3846
3847         emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
3848
3849         if (acfg->aot_opts.bind_to_runtime_version)
3850                 emit_string_symbol (acfg, "mono_runtime_version", FULL_VERSION);
3851         else
3852                 emit_string_symbol (acfg, "mono_runtime_version", "");
3853 }
3854
3855 int
3856 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
3857 {
3858         MonoImage *image = ass->image;
3859         char *symbol;
3860         int i, res;
3861         MonoAotCompile *acfg;
3862
3863         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
3864
3865         acfg = g_new0 (MonoAotCompile, 1);
3866         acfg->methods = g_ptr_array_new ();
3867         acfg->method_indexes = g_hash_table_new (NULL, NULL);
3868         acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
3869         acfg->patch_to_plt_offset = g_hash_table_new (NULL, NULL);
3870         acfg->patch_to_plt_offset_wrapper = g_malloc0 (sizeof (GHashTable*) * 128);
3871         acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3872         acfg->shared_patches = g_ptr_array_new ();
3873         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
3874         acfg->token_info_hash = g_hash_table_new (NULL, NULL);
3875         acfg->image_hash = g_hash_table_new (NULL, NULL);
3876         acfg->image_table = g_ptr_array_new ();
3877         acfg->image = image;
3878         acfg->opts = opts;
3879         acfg->mempool = mono_mempool_new ();
3880
3881         mono_aot_parse_options (aot_options, &acfg->aot_opts);
3882
3883         load_profile_files (acfg);
3884
3885         emit_start (acfg);
3886
3887         acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 1024 : 0;
3888
3889         acfg->method_index = 1;
3890
3891         /* Collect methods */
3892         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
3893                 MonoMethod *method;
3894                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3895
3896                 method = mono_get_method (acfg->image, token, NULL);
3897
3898                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3899                         /* Compile the wrapper instead */
3900                         /* We do this here instead of add_wrappers () because it is easy to do it here */
3901                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc);
3902                         method = wrapper;
3903                 }
3904
3905                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
3906                 add_method_with_index (acfg, method, i);
3907                 acfg->method_index ++;
3908         }
3909
3910         if (acfg->aot_opts.full_aot)
3911                 add_wrappers (acfg);
3912
3913         acfg->nmethods = acfg->methods->len;
3914         acfg->cfgs = g_new0 (MonoCompile*, acfg->nmethods + 32);
3915         acfg->method_got_offsets = g_new0 (guint32, acfg->nmethods + 32);
3916
3917         /* PLT offset 0 is reserved for the PLT trampoline */
3918         acfg->plt_offset = 1;
3919
3920         /* Compile methods */
3921         for (i = 0; i < acfg->methods->len; ++i) {
3922                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
3923         }
3924
3925         alloc_got_slots (acfg);
3926
3927         emit_code (acfg);
3928
3929         emit_info (acfg);
3930
3931         emit_wrapper_info (acfg);
3932
3933         emit_method_order (acfg);
3934
3935         emit_trampolines (acfg);
3936
3937         emit_class_name_table (acfg);
3938
3939         emit_got_info (acfg);
3940
3941         emit_exception_info (acfg);
3942
3943         emit_class_info (acfg);
3944
3945         emit_plt (acfg);
3946
3947         emit_image_table (acfg);
3948
3949         emit_got (acfg);
3950
3951         emit_globals (acfg);
3952
3953         symbol = g_strdup_printf ("mem_end");
3954         emit_section_change (acfg, ".text", 1);
3955         emit_global (acfg, symbol, FALSE);
3956         emit_alignment (acfg, 8);
3957         emit_label (acfg, symbol);
3958
3959         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)));
3960
3961         res = emit_writeout (acfg);
3962         if (res != 0)
3963                 return res;
3964
3965         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);
3966         printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
3967         printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
3968         printf ("%d methods contain wrapper references (%d%%)\n", acfg->stats.wrappercount, acfg->stats.mcount ? (acfg->stats.wrappercount * 100) / acfg->stats.mcount : 100);
3969         printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
3970         printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
3971         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);
3972         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
3973
3974         printf ("GOT slot distribution:\n");
3975         for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
3976                 if (acfg->stats.got_slot_types [i])
3977                         printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
3978
3979         return 0;
3980 }
3981
3982 #else
3983
3984 /* AOT disabled */
3985
3986 int
3987 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
3988 {
3989         return 0;
3990 }
3991
3992 #endif