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