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