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