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