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