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