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