2 * aot.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
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
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.
28 #include <sys/types.h>
38 #ifndef PLATFORM_WIN32
48 #include <limits.h> /* for PAGESIZE */
53 #include <mono/metadata/tabledefs.h>
54 #include <mono/metadata/class.h>
55 #include <mono/metadata/object.h>
56 #include <mono/metadata/tokentype.h>
57 #include <mono/metadata/appdomain.h>
58 #include <mono/metadata/debug-helpers.h>
59 #include <mono/metadata/assembly.h>
60 #include <mono/metadata/metadata-internals.h>
61 #include <mono/metadata/marshal.h>
62 #include <mono/metadata/gc-internal.h>
63 #include <mono/metadata/method-builder.h>
64 #include <mono/metadata/monitor.h>
65 #include <mono/utils/mono-logger.h>
66 #include <mono/utils/mono-compiler.h>
67 #include <mono/utils/mono-time.h>
74 #define TV_DECLARE(name) gint64 name
75 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
76 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
79 #define SHARED_EXT ".dll"
80 #elif defined(__ppc__) && defined(__MACH__)
81 #define SHARED_EXT ".dylib"
83 #define SHARED_EXT ".so"
86 #if defined(sparc) || defined(__ppc__) || defined(__powerpc__) || defined(__MACH__)
87 #define AS_STRING_DIRECTIVE ".asciz"
90 #define AS_STRING_DIRECTIVE ".string"
95 // .byte generates 1 byte per expression.
96 // .short generates 2 bytes per expression.
97 // .long generates 4 bytes per expression.
98 // .quad generates 8 bytes per expression.
100 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
101 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
103 typedef struct MonoAotOptions {
106 gboolean write_symbols;
107 gboolean metadata_only;
108 gboolean bind_to_runtime_version;
111 gboolean static_link;
116 typedef struct MonoAotStats {
117 int ccount, mcount, lmfcount, abscount, wrappercount, gcount, ocount, genericcount;
118 int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
119 int methods_without_got_slots, direct_calls, all_calls;
121 int got_slot_types [MONO_PATCH_INFO_NONE];
122 int jit_time, gen_time, link_time;
125 #if defined(__x86_64__) && defined(HAVE_ELF_H)
126 #define USE_ELF_WRITER 1
127 #define USE_ELF_RELA 1
130 //#define USE_ELF_WRITER 1
132 #if defined(USE_ELF_WRITER)
133 #define USE_BIN_WRITER 1
136 #ifdef USE_BIN_WRITER
138 typedef struct _BinSymbol BinSymbol;
139 typedef struct _BinReloc BinReloc;
140 typedef struct _BinSection BinSection;
154 typedef struct MonoAotCompile {
157 GHashTable *method_indexes;
160 GHashTable *patch_to_plt_offset;
161 GHashTable *plt_offset_to_patch;
162 GHashTable *patch_to_shared_got_offset;
163 GPtrArray *shared_patches;
164 GHashTable *image_hash;
165 GHashTable *method_to_cfg;
166 GHashTable *token_info_hash;
167 GPtrArray *extra_methods;
168 GPtrArray *image_table;
171 /* Number of trampolines emitted into the AOT file */
172 guint32 num_aot_trampolines;
173 guint32 got_offset, plt_offset;
174 /* Number of GOT entries reserved for trampolines */
175 guint32 num_trampoline_got_entries;
176 MonoAotOptions aot_opts;
179 MonoMemPool *mempool;
182 char *static_linking_symbol;
183 CRITICAL_SECTION mutex;
184 #ifdef USE_BIN_WRITER
186 BinSection *sections;
187 BinSection *cur_section;
188 BinReloc *relocations;
194 int mode; /* emit mode */
195 int col_count; /* bytes emitted per .byte line */
199 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
200 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
202 #ifdef HAVE_ARRAY_ELEM_INIT
203 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
204 #define MSGSTRFIELD1(line) str##line
205 static const struct msgstr_t {
206 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
207 #include "patch-info.h"
210 #define PATCH_INFO(a,b) b,
211 #include "patch-info.h"
214 static const gint16 opidx [] = {
215 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
216 #include "patch-info.h"
221 get_patch_name (int info)
223 return (const char*)&opstr + opidx [info];
227 #define PATCH_INFO(a,b) b,
228 static const char* const
229 patch_types [MONO_PATCH_INFO_NUM + 1] = {
230 #include "patch-info.h"
235 get_patch_name (int info)
237 return patch_types [info];
243 emit_global (MonoAotCompile *acfg, const char *name, gboolean func);
246 is_got_patch (MonoJumpInfoType patch_type)
251 static G_GNUC_UNUSED int
252 ilog2(register int value)
255 while (value & ~0xf) count += 4, value >>= 4;
256 while (value) count++, value >>= 1;
260 #ifdef USE_BIN_WRITER
262 typedef struct _BinLabel BinLabel;
273 BinSection *val2_section;
285 gboolean is_function;
303 emit_start (MonoAotCompile *acfg)
305 acfg->labels = g_hash_table_new (g_str_hash, g_str_equal);
309 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
313 if (acfg->cur_section && acfg->cur_section->subsection == subsection_index
314 && strcmp (acfg->cur_section->name, section_name) == 0)
316 for (section = acfg->sections; section; section = section->next) {
317 if (section->subsection == subsection_index && strcmp (section->name, section_name) == 0) {
318 acfg->cur_section = section;
323 section = g_new0 (BinSection, 1);
324 section->name = g_strdup (section_name);
325 section->subsection = subsection_index;
326 section->next = acfg->sections;
327 acfg->sections = section;
328 acfg->cur_section = section;
333 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
335 BinSymbol *symbol = g_new0 (BinSymbol, 1);
336 symbol->name = g_strdup (name);
337 symbol->is_function = func;
338 symbol->is_global = TRUE;
339 symbol->section = acfg->cur_section;
340 /* FIXME: we align after this call... */
341 symbol->offset = symbol->section->cur_offset;
342 symbol->next = acfg->symbols;
343 acfg->symbols = symbol;
347 emit_label (MonoAotCompile *acfg, const char *name)
349 BinLabel *label = g_new0 (BinLabel, 1);
350 label->name = g_strdup (name);
351 label->section = acfg->cur_section;
352 label->offset = acfg->cur_section->cur_offset;
353 g_hash_table_insert (acfg->labels, label->name, label);
357 emit_ensure_buffer (BinSection *section, int size)
359 int new_offset = section->cur_offset + size;
360 if (new_offset >= section->data_len) {
361 int new_size = section->data_len? section->data_len * 2: 256;
363 while (new_size <= new_offset)
365 data = g_malloc0 (new_size);
366 memcpy (data, section->data, section->data_len);
367 g_free (section->data);
368 section->data = data;
369 section->data_len = new_size;
374 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
376 emit_ensure_buffer (acfg->cur_section, size);
377 memcpy (acfg->cur_section->data + acfg->cur_section->cur_offset, buf, size);
378 acfg->cur_section->cur_offset += size;
382 emit_string (MonoAotCompile *acfg, const char *value)
384 int size = strlen (value) + 1;
385 emit_bytes (acfg, (const guint8*)value, size);
389 emit_line (MonoAotCompile *acfg)
391 /* Nothing to do in binary writer */
395 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
397 emit_section_change (acfg, ".text", 1);
398 emit_global (acfg, name, FALSE);
399 emit_label (acfg, name);
400 emit_string (acfg, value);
404 emit_alignment (MonoAotCompile *acfg, int size)
406 int offset = acfg->cur_section->cur_offset;
408 offset += (size - 1);
409 offset &= ~(size - 1);
410 add = offset - acfg->cur_section->cur_offset;
412 emit_ensure_buffer (acfg->cur_section, add);
413 acfg->cur_section->cur_offset += add;
418 emit_pointer (MonoAotCompile *acfg, const char *target)
424 g_assert_not_reached ();
425 emit_alignment (acfg, sizeof (gpointer));
426 reloc = g_new0 (BinReloc, 1);
427 reloc->val1 = g_strdup (target);
428 reloc->section = acfg->cur_section;
429 reloc->section_offset = acfg->cur_section->cur_offset;
430 reloc->next = acfg->relocations;
431 acfg->relocations = reloc;
432 if (strcmp (reloc->section->name, ".data") == 0) {
434 g_print ("reloc: %s at %d\n", target, acfg->cur_section->cur_offset);
436 acfg->cur_section->cur_offset += sizeof (gpointer);
440 emit_int16 (MonoAotCompile *acfg, int value)
443 emit_ensure_buffer (acfg->cur_section, 2);
444 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
445 acfg->cur_section->cur_offset += 2;
446 /* FIXME: little endian */
448 data [1] = value >> 8;
452 emit_int32 (MonoAotCompile *acfg, int value)
455 emit_ensure_buffer (acfg->cur_section, 4);
456 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
457 acfg->cur_section->cur_offset += 4;
458 /* FIXME: little endian */
460 data [1] = value >> 8;
461 data [2] = value >> 16;
462 data [3] = value >> 24;
466 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
469 reloc = mono_mempool_alloc0 (acfg->mempool, sizeof (BinReloc));
470 reloc->val1 = mono_mempool_strdup (acfg->mempool, end);
471 if (strcmp (start, ".") == 0) {
472 reloc->val2_section = acfg->cur_section;
473 reloc->val2_offset = acfg->cur_section->cur_offset;
475 reloc->val2 = mono_mempool_strdup (acfg->mempool, start);
477 reloc->offset = offset;
478 reloc->section = acfg->cur_section;
479 reloc->section_offset = acfg->cur_section->cur_offset;
480 reloc->next = acfg->relocations;
481 acfg->relocations = reloc;
482 acfg->cur_section->cur_offset += 4;
483 /*if (strcmp (reloc->section->name, ".data") == 0) {
485 g_print ("reloc: %s - %s + %d at %d\n", end, start, offset, acfg->cur_section->cur_offset - 4);
490 emit_zero_bytes (MonoAotCompile *acfg, int num)
492 emit_ensure_buffer (acfg->cur_section, num);
493 acfg->cur_section->cur_offset += num;
496 #ifdef USE_ELF_WRITER
516 #if SIZEOF_VOID_P == 4
518 typedef Elf32_Ehdr ElfHeader;
519 typedef Elf32_Shdr ElfSectHeader;
520 typedef Elf32_Phdr ElfProgHeader;
521 typedef Elf32_Sym ElfSymbol;
522 typedef Elf32_Rel ElfReloc;
523 typedef Elf32_Rela ElfRelocA;
524 typedef Elf32_Dyn ElfDynamic;
528 typedef Elf64_Ehdr ElfHeader;
529 typedef Elf64_Shdr ElfSectHeader;
530 typedef Elf64_Phdr ElfProgHeader;
531 typedef Elf64_Sym ElfSymbol;
532 typedef Elf64_Rel ElfReloc;
533 typedef Elf64_Rela ElfRelocA;
534 typedef Elf64_Dyn ElfDynamic;
546 static SectInfo section_info [] = {
548 {".hash", SHT_HASH, 4, 2, SIZEOF_VOID_P},
549 {".dynsym", SHT_DYNSYM, sizeof (ElfSymbol), 2, SIZEOF_VOID_P},
550 {".dynstr", SHT_STRTAB, 0, 2, 1},
551 {".rel.dyn", SHT_REL, sizeof (ElfReloc), 2, SIZEOF_VOID_P},
552 {".rela.dyn", SHT_RELA, sizeof (ElfRelocA), 2, SIZEOF_VOID_P},
553 {".text", SHT_PROGBITS, 0, 6, 4096},
554 {".dynamic", SHT_DYNAMIC, sizeof (ElfDynamic), 3, SIZEOF_VOID_P},
555 {".got.plt", SHT_PROGBITS, SIZEOF_VOID_P, 3, SIZEOF_VOID_P},
556 {".data", SHT_PROGBITS, 0, 3, 8},
557 {".bss", SHT_NOBITS, 0, 3, 8},
558 {".shstrtab", SHT_STRTAB, 0, 0, 1},
559 {".symtab", SHT_SYMTAB, sizeof (ElfSymbol), 0, SIZEOF_VOID_P},
560 {".strtab", SHT_STRTAB, 0, 0, 1}
569 str_table_add (ElfStrTable *table, const char* value)
573 table->data = g_string_new_len ("", 1);
574 table->hash = g_hash_table_new (g_str_hash, g_str_equal);
576 idx = GPOINTER_TO_UINT (g_hash_table_lookup (table->hash, value));
579 idx = table->data->len;
580 g_string_append (table->data, value);
581 g_string_append_c (table->data, 0);
582 g_hash_table_insert (table->hash, (void*)value, GUINT_TO_POINTER (idx));
587 append_subsection (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection *sect, BinSection *add)
589 int offset = sect->cur_offset;
590 /*offset += (sheaders [sect->shidx].sh_addralign - 1);
591 offset &= ~(sheaders [sect->shidx].sh_addralign - 1);*/
594 emit_ensure_buffer (sect, offset);
595 g_print ("section %s aligned to %d from %d\n", sect->name, offset, sect->cur_offset);
596 sect->cur_offset = offset;
598 emit_ensure_buffer (sect, add->cur_offset);
599 memcpy (sect->data + sect->cur_offset, add->data, add->cur_offset);
601 sect->cur_offset += add->cur_offset;
602 add->cur_offset = offset; /* it becomes the offset in the parent section */
603 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);
608 /* merge the subsections */
610 collect_sections (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection **out, int num)
612 int i, j, maxs, num_sections;
617 for (sect = acfg->sections; sect; sect = sect->next) {
618 if (sect->subsection == 0) {
619 out [num_sections++] = sect;
620 g_assert (num_sections < num);
621 if (strcmp (sect->name, ".text") == 0) {
622 sect->shidx = SECT_TEXT;
623 } else if (strcmp (sect->name, ".data") == 0) {
624 sect->shidx = SECT_DATA;
625 } else if (strcmp (sect->name, ".bss") == 0) {
626 sect->shidx = SECT_BSS;
629 maxs = MAX (maxs, sect->subsection);
631 for (i = 0; i < num_sections; i++) {
632 for (j = 1; j <= maxs; ++j) {
633 for (sect = acfg->sections; sect; sect = sect->next) {
634 if (sect->subsection == j && strcmp (out [i]->name, sect->name) == 0) {
635 append_subsection (acfg, sheaders, out [i], sect);
644 elf_hash (const unsigned char *name)
646 unsigned long h = 0, g;
648 h = (h << 4) + *name++;
649 if ((g = h & 0xf0000000))
656 #define NUM_BUCKETS 17
659 build_hash (MonoAotCompile *acfg, int num_sections, ElfStrTable *dynstr)
662 int num_symbols = 1 + num_sections + 3;
665 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
666 if (!symbol->is_global)
669 str_table_add (dynstr, symbol->name);
670 /*g_print ("adding sym: %s\n", symbol->name);*/
672 str_table_add (dynstr, "__bss_start");
673 str_table_add (dynstr, "_edata");
674 str_table_add (dynstr, "_end");
676 data = g_new0 (int, num_symbols + 2 + NUM_BUCKETS);
677 data [0] = NUM_BUCKETS;
678 data [1] = num_symbols;
684 get_label_addr (MonoAotCompile *acfg, const char *name)
691 lab = g_hash_table_lookup (acfg->labels, name);
692 section = lab->section;
693 offset = lab->offset;
694 if (section->parent) {
695 value = section->parent->virt_offset + section->cur_offset + offset;
697 value = section->virt_offset + offset;
703 collect_syms (MonoAotCompile *acfg, int *hash, ElfStrTable *strtab, ElfSectHeader *sheaders, int *num_syms)
714 symbols = g_new0 (ElfSymbol, hash [1]);
716 symbols = g_new0 (ElfSymbol, *num_syms + SECT_NUM + 10); /* FIXME */
718 /* the first symbol is undef, all zeroes */
722 for (j = 1; j < SECT_NUM; ++j) {
723 symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
724 symbols [i].st_shndx = j;
725 symbols [i].st_value = sheaders [j].sh_addr;
729 for (section = acfg->sections; section; section = section->next) {
732 symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
733 if (strcmp (section->name, ".text") == 0) {
734 symbols [i].st_shndx = SECT_TEXT;
735 section->shidx = SECT_TEXT;
736 section->file_offset = 4096;
737 symbols [i].st_value = section->virt_offset;
738 } else if (strcmp (section->name, ".data") == 0) {
739 symbols [i].st_shndx = SECT_DATA;
740 section->shidx = SECT_DATA;
741 section->file_offset = 4096 + 28; /* FIXME */
742 symbols [i].st_value = section->virt_offset;
743 } else if (strcmp (section->name, ".bss") == 0) {
744 symbols [i].st_shndx = SECT_BSS;
745 section->shidx = SECT_BSS;
746 section->file_offset = 4096 + 28 + 8; /* FIXME */
747 symbols [i].st_value = section->virt_offset;
752 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
755 if (!symbol->is_global)
757 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, symbol->is_function? STT_FUNC : STT_OBJECT);
758 symbols [i].st_name = str_table_add (strtab, symbol->name);
759 /*g_print ("sym name %s tabled to %d\n", symbol->name, symbols [i].st_name);*/
760 section = symbol->section;
761 symbols [i].st_shndx = section->parent? section->parent->shidx: section->shidx;
762 lab = g_hash_table_lookup (acfg->labels, symbol->name);
763 offset = lab->offset;
764 if (section->parent) {
765 symbols [i].st_value = section->parent->virt_offset + section->cur_offset + offset;
767 symbols [i].st_value = section->virt_offset + offset;
771 /* add special symbols */
772 symbols [i].st_name = str_table_add (strtab, "__bss_start");
773 symbols [i].st_shndx = 0xfff1;
774 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
776 symbols [i].st_name = str_table_add (strtab, "_edata");
777 symbols [i].st_shndx = 0xfff1;
778 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
780 symbols [i].st_name = str_table_add (strtab, "_end");
781 symbols [i].st_shndx = 0xfff1;
782 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
788 /* add to hash table */
791 chain = hash + 2 + hash [0];
792 for (i = 0; i < hash [1]; ++i) {
794 /*g_print ("checking %d '%s' (sym %d)\n", symbols [i].st_name, strtab->data->str + symbols [i].st_name, i);*/
795 if (!symbols [i].st_name)
797 hashc = elf_hash ((guint8*)strtab->data->str + symbols [i].st_name);
798 slot = hashc % hash [0];
799 /*g_print ("hashing '%s' at slot %d (sym %d)\n", strtab->data->str + symbols [i].st_name, slot, i);*/
801 chain [i] = bucket [slot];
812 reloc_symbols (MonoAotCompile *acfg, ElfSymbol *symbols, ElfSectHeader *sheaders, ElfStrTable *strtab, gboolean dynamic)
820 for (section = acfg->sections; section; section = section->next) {
823 symbols [i].st_value = sheaders [section->shidx].sh_addr;
827 for (i = 1; i < SECT_NUM; ++i) {
828 symbols [i].st_value = sheaders [i].sh_addr;
831 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
834 if (dynamic && !symbol->is_global)
836 section = symbol->section;
837 lab = g_hash_table_lookup (acfg->labels, symbol->name);
838 offset = lab->offset;
839 if (section->parent) {
840 symbols [i].st_value = sheaders [section->parent->shidx].sh_addr + section->cur_offset + offset;
842 symbols [i].st_value = sheaders [section->shidx].sh_addr + offset;
847 symbols [i].st_value = sheaders [SECT_BSS].sh_addr;
850 symbols [i].st_value = sheaders [SECT_DATA].sh_addr + sheaders [SECT_DATA].sh_size;
853 symbols [i].st_value = sheaders [SECT_BSS].sh_addr + sheaders [SECT_BSS].sh_size;
858 resolve_reloc (MonoAotCompile *acfg, BinReloc *reloc, guint8 **out_data, gsize *out_vaddr, gsize *out_start_val, gsize *out_end_val)
861 gsize end_val, start_val;
864 end_val = get_label_addr (acfg, reloc->val1);
866 start_val = get_label_addr (acfg, reloc->val2);
867 } else if (reloc->val2_section) {
868 start_val = reloc->val2_offset;
869 if (reloc->val2_section->parent)
870 start_val += reloc->val2_section->parent->virt_offset + reloc->val2_section->cur_offset;
872 start_val += reloc->val2_section->virt_offset;
876 end_val = end_val - start_val + reloc->offset;
877 if (reloc->section->parent) {
878 data = reloc->section->parent->data;
879 data += reloc->section->cur_offset;
880 data += reloc->section_offset;
881 vaddr = reloc->section->parent->virt_offset;
882 vaddr += reloc->section->cur_offset;
883 vaddr += reloc->section_offset;
885 data = reloc->section->data;
886 data += reloc->section_offset;
887 vaddr = reloc->section->virt_offset;
888 vaddr += reloc->section_offset;
891 *out_start_val = start_val;
892 *out_end_val = end_val;
900 resolve_relocations (MonoAotCompile *acfg)
904 gsize end_val, start_val;
909 rr = g_new0 (ElfRelocA, acfg->num_relocs);
912 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
913 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
914 /* FIXME: little endian */
916 data [1] = end_val >> 8;
917 data [2] = end_val >> 16;
918 data [3] = end_val >> 24;
919 if (start_val == 0) {
920 rr [i].r_offset = vaddr;
921 rr [i].r_info = R_X86_64_RELATIVE;
922 rr [i].r_addend = end_val;
924 g_assert (i <= acfg->num_relocs);
930 #else /* USE_ELF_RELA */
933 resolve_relocations (MonoAotCompile *acfg)
937 gsize end_val, start_val;
942 rr = g_new0 (ElfReloc, acfg->num_relocs);
945 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
946 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
947 /* FIXME: little endian */
949 data [1] = end_val >> 8;
950 data [2] = end_val >> 16;
951 data [3] = end_val >> 24;
952 if (start_val == 0) {
953 rr [i].r_offset = vaddr;
954 rr [i].r_info = 8; /* FIXME: 386_RELATIVE */
956 g_assert (i <= acfg->num_relocs);
962 #endif /* USE_ELF_RELA */
965 emit_writeout (MonoAotCompile *acfg)
967 char *outfile_name, *tmp_outfile_name;
970 ElfProgHeader progh [3];
971 ElfSectHeader secth [SECT_NUM];
977 ElfStrTable str_table = {NULL, NULL};
978 ElfStrTable sh_str_table = {NULL, NULL};
979 ElfStrTable dyn_str_table = {NULL, NULL};
980 BinSection* sections [6];
981 BinSection *text_section = NULL, *data_section = NULL, *bss_section = NULL;
984 ElfDynamic dynamic [14];
986 int i, num_sections, file_offset, virt_offset, size, num_symtab;
989 g_assert (!acfg->aot_opts.asm_only);
991 if (acfg->aot_opts.outfile)
992 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
994 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
996 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
998 unlink (tmp_outfile_name);
999 file = fopen (tmp_outfile_name, "w");
1002 /* Section headers */
1003 memset (§h, 0, sizeof (secth));
1004 memset (&dynamic, 0, sizeof (dynamic));
1005 memset (&header, 0, sizeof (header));
1007 for (i = 1; i < SECT_NUM; ++i) {
1008 secth [i].sh_name = str_table_add (&sh_str_table, section_info [i].name);
1009 secth [i].sh_type = section_info [i].type;
1010 secth [i].sh_addralign = section_info [i].align;
1011 secth [i].sh_flags = section_info [i].flags;
1012 secth [i].sh_entsize = section_info [i].esize;
1014 secth [SECT_DYNSYM].sh_info = SIZEOF_VOID_P == 4 ? 4 : 2;
1015 secth [SECT_SYMTAB].sh_info = SIZEOF_VOID_P == 4 ? 20 : 17;
1016 secth [SECT_HASH].sh_link = SECT_DYNSYM;
1017 secth [SECT_DYNSYM].sh_link = SECT_DYNSTR;
1018 secth [SECT_REL_DYN].sh_link = SECT_DYNSYM;
1019 secth [SECT_RELA_DYN].sh_link = SECT_DYNSYM;
1020 secth [SECT_DYNAMIC].sh_link = SECT_DYNSTR;
1021 secth [SECT_SYMTAB].sh_link = SECT_STRTAB;
1023 num_sections = collect_sections (acfg, secth, sections, 6);
1024 hash = build_hash (acfg, num_sections, &dyn_str_table);
1025 num_symtab = hash [1]; /* FIXME */
1026 g_print ("num_sections: %d\n", num_sections);
1027 g_print ("dynsym: %d, dynstr size: %d\n", hash [1], (int)dyn_str_table.data->len);
1028 for (i = 0; i < num_sections; ++i) {
1029 g_print ("section %s, size: %d, %x\n", sections [i]->name, sections [i]->cur_offset, sections [i]->cur_offset);
1032 /* at this point we know where in the file the first segment sections go */
1033 dynsym = collect_syms (acfg, hash, &dyn_str_table, NULL, NULL);
1034 num_local_syms = hash [1];
1035 symtab = collect_syms (acfg, NULL, &str_table, secth, &num_local_syms);
1037 for (i = 0; i < num_sections; ++i) {
1038 if (sections [i]->shidx == SECT_TEXT) {
1039 text_section = sections [i];
1040 } else if (sections [i]->shidx == SECT_DATA) {
1041 data_section = sections [i];
1042 } else if (sections [i]->shidx == SECT_BSS) {
1043 bss_section = sections [i];
1047 file_offset = virt_offset = sizeof (header) + sizeof (progh);
1048 secth [SECT_HASH].sh_addr = secth [SECT_HASH].sh_offset = file_offset;
1049 size = sizeof (int) * (2 + hash [0] + hash [1]);
1050 virt_offset = (file_offset += size);
1051 secth [SECT_HASH].sh_size = size;
1052 secth [SECT_DYNSYM].sh_addr = secth [SECT_DYNSYM].sh_offset = file_offset;
1053 size = sizeof (ElfSymbol) * hash [1];
1054 virt_offset = (file_offset += size);
1055 secth [SECT_DYNSYM].sh_size = size;
1056 secth [SECT_DYNSTR].sh_addr = secth [SECT_DYNSTR].sh_offset = file_offset;
1057 size = dyn_str_table.data->len;
1058 virt_offset = (file_offset += size);
1059 secth [SECT_DYNSTR].sh_size = size;
1061 file_offset &= ~(4-1);
1062 secth [SECT_REL_DYN].sh_addr = secth [SECT_REL_DYN].sh_offset = file_offset;
1063 #ifndef USE_ELF_RELA
1064 size = sizeof (ElfReloc) * acfg->num_relocs;
1068 virt_offset = (file_offset += size);
1069 secth [SECT_REL_DYN].sh_size = size;
1070 secth [SECT_RELA_DYN].sh_addr = secth [SECT_RELA_DYN].sh_offset = file_offset;
1072 size = sizeof (ElfRelocA) * acfg->num_relocs;
1076 virt_offset = (file_offset += size);
1077 secth [SECT_RELA_DYN].sh_size = size;
1078 file_offset += 4096-1;
1079 file_offset &= ~(4096-1);
1080 virt_offset = file_offset;
1081 secth [SECT_TEXT].sh_addr = secth [SECT_TEXT].sh_offset = file_offset;
1082 size = text_section->cur_offset;
1083 secth [SECT_TEXT].sh_size = size;
1084 file_offset += size;
1086 file_offset &= ~(4-1);
1087 virt_offset = file_offset;
1088 /* .dynamic, .got.plt, .data, .bss here */
1089 /* Have to increase the virt offset since these go to a separate segment */
1090 virt_offset += PAGESIZE;
1091 secth [SECT_DYNAMIC].sh_addr = virt_offset;
1092 secth [SECT_DYNAMIC].sh_offset = file_offset;
1093 size = sizeof (dynamic);
1094 secth [SECT_DYNAMIC].sh_size = size;
1097 file_offset += size;
1098 virt_offset += size;
1099 secth [SECT_GOT_PLT].sh_addr = virt_offset;
1100 secth [SECT_GOT_PLT].sh_offset = file_offset;
1102 secth [SECT_GOT_PLT].sh_size = size;
1105 file_offset += size;
1106 virt_offset += size;
1107 secth [SECT_DATA].sh_addr = virt_offset;
1108 secth [SECT_DATA].sh_offset = file_offset;
1109 size = data_section->cur_offset;
1110 secth [SECT_DATA].sh_size = size;
1113 file_offset += size;
1114 virt_offset += size;
1115 secth [SECT_BSS].sh_addr = virt_offset;
1116 secth [SECT_BSS].sh_offset = file_offset;
1117 size = bss_section->cur_offset;
1118 secth [SECT_BSS].sh_size = size;
1120 /* virtual doesn't matter anymore */
1121 secth [SECT_SHSTRTAB].sh_offset = file_offset;
1122 size = sh_str_table.data->len;
1123 secth [SECT_SHSTRTAB].sh_size = size;
1124 size += SIZEOF_VOID_P-1;
1125 size &= ~(SIZEOF_VOID_P-1);
1126 file_offset += size;
1127 secth [SECT_SYMTAB].sh_offset = file_offset;
1128 size = sizeof (ElfSymbol) * num_local_syms;
1129 secth [SECT_SYMTAB].sh_size = size;
1130 file_offset += size;
1131 secth [SECT_STRTAB].sh_offset = file_offset;
1132 size = str_table.data->len;
1133 secth [SECT_STRTAB].sh_size = size;
1134 file_offset += size;
1136 file_offset &= ~(4-1);
1138 text_section->file_offset = secth [SECT_TEXT].sh_offset;
1139 text_section->virt_offset = secth [SECT_TEXT].sh_addr;
1140 data_section->file_offset = secth [SECT_DATA].sh_offset;
1141 data_section->virt_offset = secth [SECT_DATA].sh_addr;
1142 bss_section->file_offset = secth [SECT_BSS].sh_offset;
1143 bss_section->virt_offset = secth [SECT_BSS].sh_addr;
1145 header.e_ident [EI_MAG0] = ELFMAG0;
1146 header.e_ident [EI_MAG1] = ELFMAG1;
1147 header.e_ident [EI_MAG2] = ELFMAG2;
1148 header.e_ident [EI_MAG3] = ELFMAG3;
1149 header.e_ident [EI_CLASS] = SIZEOF_VOID_P == 4 ? ELFCLASS32 : ELFCLASS64;
1150 header.e_ident [EI_DATA] = ELFDATA2LSB;
1151 header.e_ident [EI_VERSION] = EV_CURRENT;
1152 header.e_ident [EI_OSABI] = ELFOSABI_NONE;
1153 header.e_ident [EI_ABIVERSION] = 0;
1154 for (i = EI_PAD; i < EI_NIDENT; ++i)
1155 header.e_ident [i] = 0;
1157 header.e_type = ET_DYN;
1158 #if defined(__i386__)
1159 header.e_machine = EM_386;
1160 #elif defined(__x86_64__)
1161 header.e_machine = EM_X86_64;
1163 g_assert_not_reached ();
1165 header.e_version = 1;
1167 header.e_phoff = sizeof (header);
1168 header.e_ehsize = sizeof (header);
1169 header.e_phentsize = sizeof (ElfProgHeader);
1171 header.e_entry = secth [SECT_TEXT].sh_addr;
1172 header.e_shstrndx = SECT_SHSTRTAB;
1173 header.e_shentsize = sizeof (ElfSectHeader);
1174 header.e_shnum = SECT_NUM;
1175 header.e_shoff = file_offset;
1179 dynamic [i].d_tag = DT_HASH;
1180 dynamic [i].d_un.d_val = secth [SECT_HASH].sh_offset;
1182 dynamic [i].d_tag = DT_STRTAB;
1183 dynamic [i].d_un.d_val = secth [SECT_DYNSTR].sh_offset;
1185 dynamic [i].d_tag = DT_SYMTAB;
1186 dynamic [i].d_un.d_val = secth [SECT_DYNSYM].sh_offset;
1188 dynamic [i].d_tag = DT_STRSZ;
1189 dynamic [i].d_un.d_val = dyn_str_table.data->len;
1191 dynamic [i].d_tag = DT_SYMENT;
1192 dynamic [i].d_un.d_val = sizeof (ElfSymbol);
1195 dynamic [i].d_tag = DT_RELA;
1196 dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_offset;
1198 dynamic [i].d_tag = DT_RELASZ;
1199 dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_size;
1201 dynamic [i].d_tag = DT_RELAENT;
1202 dynamic [i].d_un.d_val = sizeof (ElfRelocA);
1205 dynamic [i].d_tag = DT_REL;
1206 dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_offset;
1208 dynamic [i].d_tag = DT_RELSZ;
1209 dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_size;
1211 dynamic [i].d_tag = DT_RELENT;
1212 dynamic [i].d_un.d_val = sizeof (ElfReloc);
1215 dynamic [i].d_tag = DT_RELCOUNT;
1216 dynamic [i].d_un.d_val = acfg->num_relocs;
1219 /* Program header */
1220 memset (&progh, 0, sizeof (progh));
1221 progh [0].p_type = PT_LOAD;
1222 progh [0].p_filesz = progh [0].p_memsz = secth [SECT_DYNAMIC].sh_offset;
1223 progh [0].p_align = 4096;
1224 progh [0].p_flags = 5;
1226 progh [1].p_type = PT_LOAD;
1227 progh [1].p_offset = secth [SECT_DYNAMIC].sh_offset;
1228 progh [1].p_vaddr = progh [1].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1229 progh [1].p_filesz = secth [SECT_BSS].sh_offset - secth [SECT_DYNAMIC].sh_offset;
1230 progh [1].p_memsz = secth [SECT_BSS].sh_addr + secth [SECT_BSS].sh_size - secth [SECT_DYNAMIC].sh_addr;
1231 progh [1].p_align = 4096;
1232 progh [1].p_flags = 6;
1234 progh [2].p_type = PT_DYNAMIC;
1235 progh [2].p_offset = secth [SECT_DYNAMIC].sh_offset;
1236 progh [2].p_vaddr = progh [2].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1237 progh [2].p_filesz = progh [2].p_memsz = secth [SECT_DYNAMIC].sh_size;
1238 progh [2].p_align = SIZEOF_VOID_P;
1239 progh [2].p_flags = 6;
1241 reloc_symbols (acfg, dynsym, secth, &dyn_str_table, TRUE);
1242 reloc_symbols (acfg, symtab, secth, &str_table, FALSE);
1243 relocs = resolve_relocations (acfg);
1245 fwrite (&header, sizeof (header), 1, file);
1246 fwrite (&progh, sizeof (progh), 1, file);
1247 fwrite (hash, sizeof (int) * (hash [0] + hash [1] + 2), 1, file);
1248 fwrite (dynsym, sizeof (ElfSymbol) * hash [1], 1, file);
1249 fwrite (dyn_str_table.data->str, dyn_str_table.data->len, 1, file);
1251 fseek (file, secth [SECT_REL_DYN].sh_offset, SEEK_SET);
1252 fwrite (relocs, sizeof (ElfReloc), acfg->num_relocs, file);
1255 fseek (file, secth [SECT_RELA_DYN].sh_offset, SEEK_SET);
1256 fwrite (relocs, secth [SECT_RELA_DYN].sh_size, 1, file);
1258 fseek (file, secth [SECT_TEXT].sh_offset, SEEK_SET);
1259 /* write .text, .data, .bss sections */
1260 fwrite (text_section->data, text_section->cur_offset, 1, file);
1263 fwrite (dynamic, sizeof (dynamic), 1, file);
1265 size = secth [SECT_DYNAMIC].sh_addr;
1266 fwrite (&size, sizeof (size), 1, file);
1267 fseek (file, secth [SECT_DATA].sh_offset, SEEK_SET);
1268 fwrite (data_section->data, data_section->cur_offset, 1, file);
1270 fseek (file, secth [SECT_SHSTRTAB].sh_offset, SEEK_SET);
1271 fwrite (sh_str_table.data->str, sh_str_table.data->len, 1, file);
1272 fseek (file, secth [SECT_SYMTAB].sh_offset, SEEK_SET);
1273 fwrite (symtab, sizeof (ElfSymbol) * num_local_syms, 1, file);
1274 fseek (file, secth [SECT_STRTAB].sh_offset, SEEK_SET);
1275 fwrite (str_table.data->str, str_table.data->len, 1, file);
1276 /*g_print ("file_offset %d vs %d\n", file_offset, ftell (file));*/
1277 /*g_assert (file_offset >= ftell (file));*/
1278 fseek (file, file_offset, SEEK_SET);
1279 fwrite (§h, sizeof (secth), 1, file);
1281 rename (tmp_outfile_name, outfile_name);
1283 g_free (tmp_outfile_name);
1284 g_free (outfile_name);
1289 #endif /* USE_ELF_WRITER */
1294 emit_start (MonoAotCompile *acfg)
1296 if (acfg->aot_opts.asm_only) {
1297 if (acfg->aot_opts.outfile)
1298 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1300 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
1301 acfg->fp = fopen (acfg->tmpfname, "w+");
1303 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
1304 acfg->fp = fdopen (i, "w+");
1306 g_assert (acfg->fp);
1310 emit_unset_mode (MonoAotCompile *acfg)
1312 if (acfg->mode == EMIT_NONE)
1314 fprintf (acfg->fp, "\n");
1315 acfg->mode = EMIT_NONE;
1319 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
1321 emit_unset_mode (acfg);
1322 #if defined(PLATFORM_WIN32)
1323 fprintf (acfg->fp, ".section %s\n", section_name);
1324 #elif defined(__MACH__)
1325 if (strcmp(section_name, ".bss") == 0)
1326 fprintf (acfg->fp, "%s\n", ".data");
1328 fprintf (acfg->fp, "%s\n", section_name);
1329 #elif defined(sparc) || defined(__arm__)
1330 /* For solaris as, GNU as should accept the same */
1331 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1333 fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1338 emit_symbol_type (MonoAotCompile *acfg, const char *name, gboolean func)
1347 emit_unset_mode (acfg);
1348 #if defined(__MACH__)
1350 #elif defined(sparc) || defined(__arm__)
1351 fprintf (acfg->fp, "\t.type %s,#%s\n", name, stype);
1352 #elif defined(PLATFORM_WIN32)
1354 #elif defined(__x86_64__) || defined(__i386__)
1355 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1357 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1362 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
1364 emit_unset_mode (acfg);
1365 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1366 // mach-o always uses a '_' prefix.
1367 fprintf (acfg->fp, "\t.globl _%s\n", name);
1369 fprintf (acfg->fp, "\t.globl %s\n", name);
1372 emit_symbol_type (acfg, name, func);
1376 emit_label (MonoAotCompile *acfg, const char *name)
1378 emit_unset_mode (acfg);
1379 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1380 // mach-o always uses a '_' prefix.
1381 fprintf (acfg->fp, "_%s:\n", name);
1383 fprintf (acfg->fp, "%s:\n", name);
1386 #if defined(PLATFORM_WIN32)
1387 /* Emit a normal label too */
1388 fprintf (acfg->fp, "%s:\n", name);
1393 emit_string (MonoAotCompile *acfg, const char *value)
1395 emit_unset_mode (acfg);
1396 fprintf (acfg->fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
1400 emit_line (MonoAotCompile *acfg)
1402 emit_unset_mode (acfg);
1403 fprintf (acfg->fp, "\n");
1407 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
1409 emit_unset_mode (acfg);
1410 emit_section_change (acfg, ".text", 1);
1411 emit_global (acfg, name, FALSE);
1412 emit_label (acfg, name);
1413 emit_string (acfg, value);
1417 emit_alignment (MonoAotCompile *acfg, int size)
1419 emit_unset_mode (acfg);
1420 #if defined(__arm__)
1421 fprintf (acfg->fp, "\t.align %d\n", ilog2 (size));
1422 #elif defined(__ppc__) && defined(__MACH__)
1423 // the mach-o assembler specifies alignments as powers of 2.
1424 fprintf (acfg->fp, "\t.align %d\t; ilog2\n", ilog2(size));
1425 #elif defined(__powerpc__)
1426 /* ignore on linux/ppc */
1428 fprintf (acfg->fp, "\t.align %d\n", size);
1433 emit_pointer (MonoAotCompile *acfg, const char *target)
1435 emit_unset_mode (acfg);
1436 emit_alignment (acfg, sizeof (gpointer));
1437 #if defined(__x86_64__)
1438 fprintf (acfg->fp, "\t.quad %s\n", target ? target : "0");
1439 #elif defined(sparc) && SIZEOF_VOID_P == 8
1440 fprintf (acfg->fp, "\t.xword %s\n", target ? target : "0");
1442 fprintf (acfg->fp, "\t.long %s\n", target ? target : "0");
1446 static char *byte_to_str;
1449 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
1452 if (acfg->mode != EMIT_BYTE) {
1453 acfg->mode = EMIT_BYTE;
1454 acfg->col_count = 0;
1457 if (byte_to_str == NULL) {
1458 byte_to_str = g_new0 (char, 256 * 8);
1459 for (i = 0; i < 256; ++i) {
1460 sprintf (byte_to_str + (i * 8), ",%d", i);
1464 for (i = 0; i < size; ++i, ++acfg->col_count) {
1465 if ((acfg->col_count % 32) == 0)
1466 fprintf (acfg->fp, "\n\t.byte %d", buf [i]);
1468 fputs (byte_to_str + (buf [i] * 8), acfg->fp);
1473 emit_int16 (MonoAotCompile *acfg, int value)
1475 if (acfg->mode != EMIT_WORD) {
1476 acfg->mode = EMIT_WORD;
1477 acfg->col_count = 0;
1479 if ((acfg->col_count++ % 8) == 0)
1480 #if defined(__MACH__)
1481 fprintf (acfg->fp, "\n\t.short ");
1482 #elif defined(__arm__)
1483 /* FIXME: Use .hword on other archs as well */
1484 fprintf (acfg->fp, "\n\t.hword ");
1486 fprintf (acfg->fp, "\n\t.word ");
1489 fprintf (acfg->fp, ", ");
1490 fprintf (acfg->fp, "%d", value);
1494 emit_int32 (MonoAotCompile *acfg, int value)
1496 if (acfg->mode != EMIT_LONG) {
1497 acfg->mode = EMIT_LONG;
1498 acfg->col_count = 0;
1500 if ((acfg->col_count++ % 8) == 0)
1501 fprintf (acfg->fp, "\n\t.long ");
1503 fprintf (acfg->fp, ",");
1504 fprintf (acfg->fp, "%d", value);
1508 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
1510 if (acfg->mode != EMIT_LONG) {
1511 acfg->mode = EMIT_LONG;
1512 acfg->col_count = 0;
1514 if ((acfg->col_count++ % 8) == 0)
1515 fprintf (acfg->fp, "\n\t.long ");
1517 fprintf (acfg->fp, ",");
1519 fprintf (acfg->fp, "%s - %s + %d", end, start, offset);
1520 else if (offset < 0)
1521 fprintf (acfg->fp, "%s - %s %d", end, start, offset);
1523 fprintf (acfg->fp, "%s - %s", end, start);
1527 emit_zero_bytes (MonoAotCompile *acfg, int num)
1529 emit_unset_mode (acfg);
1530 #if defined(__MACH__)
1531 fprintf (acfg->fp, "\t.space %d\n", num);
1533 fprintf (acfg->fp, "\t.skip %d\n", num);
1538 emit_writeout (MonoAotCompile *acfg)
1540 char *command, *objfile;
1541 char *outfile_name, *tmp_outfile_name;
1545 #if defined(__x86_64__)
1546 #define AS_OPTIONS "--64"
1547 #elif defined(sparc) && SIZEOF_VOID_P == 8
1548 #define AS_OPTIONS "-xarch=v9"
1550 #define AS_OPTIONS ""
1553 if (acfg->aot_opts.asm_only) {
1554 printf ("Output file: '%s'.\n", acfg->tmpfname);
1555 if (acfg->aot_opts.static_link)
1556 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1560 if (acfg->aot_opts.static_link) {
1561 if (acfg->aot_opts.outfile)
1562 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1564 objfile = g_strdup_printf ("%s.o", acfg->image->name);
1566 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
1568 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
1569 printf ("Executing the native assembler: %s\n", command);
1570 if (system (command) != 0) {
1578 if (acfg->aot_opts.static_link) {
1579 printf ("Output file: '%s'.\n", objfile);
1580 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1585 if (acfg->aot_opts.outfile)
1586 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1588 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1590 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1593 command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
1594 #elif defined(__ppc__) && defined(__MACH__)
1595 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
1596 #elif defined(PLATFORM_WIN32)
1597 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
1599 if (acfg->aot_opts.no_dlsym) {
1601 * Need to link using gcc so our ctor function gets called.
1603 command = g_strdup_printf ("gcc -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1605 command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1608 printf ("Executing the native linker: %s\n", command);
1609 if (system (command) != 0) {
1610 g_free (tmp_outfile_name);
1611 g_free (outfile_name);
1619 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
1620 printf ("Stripping the binary: %s\n", com);
1624 rename (tmp_outfile_name, outfile_name);
1626 g_free (tmp_outfile_name);
1627 g_free (outfile_name);
1630 if (acfg->aot_opts.save_temps)
1631 printf ("Retained input file.\n");
1633 unlink (acfg->tmpfname);
1638 #endif /* ASM_WRITER */
1641 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
1643 if (acfg->aot_opts.no_dlsym) {
1644 g_ptr_array_add (acfg->globals, g_strdup (name));
1646 emit_global_inner (acfg, name, func);
1651 emit_byte (MonoAotCompile *acfg, guint8 val)
1653 emit_bytes (acfg, &val, 1);
1657 mono_get_field_token (MonoClassField *field)
1659 MonoClass *klass = field->parent;
1662 for (i = 0; i < klass->field.count; ++i) {
1663 if (field == &klass->fields [i])
1664 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1667 g_assert_not_reached ();
1672 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1676 //printf ("ENCODE: %d 0x%x.\n", value, value);
1679 * Same encoding as the one used in the metadata, extended to handle values
1680 * greater than 0x1fffffff.
1682 if ((value >= 0) && (value <= 127))
1684 else if ((value >= 0) && (value <= 16383)) {
1685 p [0] = 0x80 | (value >> 8);
1686 p [1] = value & 0xff;
1688 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1689 p [0] = (value >> 24) | 0xc0;
1690 p [1] = (value >> 16) & 0xff;
1691 p [2] = (value >> 8) & 0xff;
1692 p [3] = value & 0xff;
1697 p [1] = (value >> 24) & 0xff;
1698 p [2] = (value >> 16) & 0xff;
1699 p [3] = (value >> 8) & 0xff;
1700 p [4] = value & 0xff;
1708 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1712 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1716 index = g_hash_table_size (cfg->image_hash);
1717 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1718 g_ptr_array_add (cfg->image_table, image);
1724 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1727 MonoClass *k = NULL;
1729 /* FIXME: Search referenced images as well */
1730 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1731 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1736 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1737 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1743 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1748 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1749 * standard metadata encoding.
1752 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1756 if (klass->generic_class) {
1758 g_assert (klass->type_token);
1760 /* Find a typespec for a class if possible */
1761 token = find_typespec_for_class (acfg, klass);
1763 encode_value (token, p, &p);
1764 encode_value (get_image_index (acfg, acfg->image), p, &p);
1766 MonoClass *gclass = klass->generic_class->container_class;
1767 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1770 /* Encode it ourselves */
1772 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1773 encode_value (MONO_TYPE_GENERICINST, p, &p);
1774 encode_klass_ref (acfg, gclass, p, &p);
1775 encode_value (inst->type_argc, p, &p);
1776 for (i = 0; i < inst->type_argc; ++i)
1777 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1779 } else if (klass->type_token) {
1780 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1781 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1782 encode_value (get_image_index (acfg, klass->image), p, &p);
1783 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1784 MonoGenericParam *param = klass->byval_arg.data.generic_param;
1787 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1788 encode_value (klass->byval_arg.type, p, &p);
1790 encode_value (param->num, p, &p);
1792 g_assert (param->owner);
1793 encode_value (param->owner->is_method, p, &p);
1794 if (param->owner->is_method)
1795 encode_method_ref (acfg, param->owner->owner.method, p, &p);
1797 encode_klass_ref (acfg, param->owner->owner.klass, p, &p);
1800 g_assert (klass->rank > 0);
1801 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1802 encode_value (get_image_index (acfg, klass->image), p, &p);
1803 encode_value (klass->rank, p, &p);
1804 encode_klass_ref (acfg, klass->element_class, p, &p);
1810 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1812 guint32 token = mono_get_field_token (field);
1815 encode_klass_ref (cfg, field->parent, p, &p);
1816 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1817 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1822 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1826 MonoGenericInst *inst;
1828 /* Encode the context */
1829 inst = context->class_inst;
1830 encode_value (inst ? 1 : 0, p, &p);
1832 encode_value (inst->type_argc, p, &p);
1833 for (i = 0; i < inst->type_argc; ++i)
1834 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1836 inst = context->method_inst;
1837 encode_value (inst ? 1 : 0, p, &p);
1839 encode_value (inst->type_argc, p, &p);
1840 for (i = 0; i < inst->type_argc; ++i)
1841 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1847 #define MAX_IMAGE_INDEX 250
1850 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1852 guint32 image_index = get_image_index (acfg, method->klass->image);
1853 guint32 token = method->token;
1854 MonoJumpInfoToken *ji;
1857 g_assert (image_index < MAX_IMAGE_INDEX);
1859 /* Mark methods which can't use aot trampolines because they need the further
1860 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1862 if (method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
1863 encode_value ((252 << 24), p, &p);
1865 if (method->wrapper_type) {
1867 encode_value ((253 << 24), p, &p);
1869 encode_value (method->wrapper_type, p, &p);
1871 switch (method->wrapper_type) {
1872 case MONO_WRAPPER_REMOTING_INVOKE:
1873 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1874 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1877 m = mono_marshal_method_from_wrapper (method);
1879 encode_method_ref (acfg, m, p, &p);
1882 case MONO_WRAPPER_PROXY_ISINST:
1883 case MONO_WRAPPER_LDFLD:
1884 case MONO_WRAPPER_LDFLDA:
1885 case MONO_WRAPPER_STFLD:
1886 case MONO_WRAPPER_ISINST: {
1887 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1888 encode_klass_ref (acfg, proxy_class, p, &p);
1891 case MONO_WRAPPER_LDFLD_REMOTE:
1892 case MONO_WRAPPER_STFLD_REMOTE:
1894 case MONO_WRAPPER_ALLOC: {
1895 int alloc_type = mono_gc_get_managed_allocator_type (method);
1896 g_assert (alloc_type != -1);
1897 encode_value (alloc_type, p, &p);
1900 case MONO_WRAPPER_STELEMREF:
1901 case MONO_WRAPPER_MONITOR_FAST_ENTER:
1902 case MONO_WRAPPER_MONITOR_FAST_EXIT:
1904 case MONO_WRAPPER_STATIC_RGCTX_INVOKE: {
1907 m = mono_marshal_method_from_wrapper (method);
1909 encode_method_ref (acfg, m, p, &p);
1913 g_assert_not_reached ();
1915 } else if (mono_method_signature (method)->is_inflated) {
1917 * This is a generic method, find the original token which referenced it and
1919 * Obtain the token from information recorded by the JIT.
1921 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1923 image_index = get_image_index (acfg, ji->image);
1924 g_assert (image_index < MAX_IMAGE_INDEX);
1928 encode_value ((255 << 24), p, &p);
1929 encode_value (image_index, p, &p);
1930 encode_value (token, p, &p);
1932 MonoMethod *declaring;
1933 MonoGenericContext *context = mono_method_get_context (method);
1935 g_assert (method->is_inflated);
1936 declaring = ((MonoMethodInflated*)method)->declaring;
1939 * This might be a non-generic method of a generic instance, which
1940 * doesn't have a token since the reference is generated by the JIT
1941 * like Nullable:Box/Unbox, or by generic sharing.
1945 encode_value ((254 << 24), p, &p);
1946 /* Encode the klass */
1947 encode_klass_ref (acfg, method->klass, p, &p);
1948 /* Encode the method */
1949 image_index = get_image_index (acfg, method->klass->image);
1950 g_assert (image_index < MAX_IMAGE_INDEX);
1951 g_assert (declaring->token);
1952 token = declaring->token;
1953 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1954 encode_value (image_index, p, &p);
1955 encode_value (token, p, &p);
1956 encode_generic_context (acfg, context, p, &p);
1958 } else if (token == 0) {
1959 /* This might be a method of a constructed type like int[,].Set */
1960 /* Obtain the token from information recorded by the JIT */
1961 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1963 image_index = get_image_index (acfg, ji->image);
1964 g_assert (image_index < MAX_IMAGE_INDEX);
1968 encode_value ((255 << 24), p, &p);
1969 encode_value (image_index, p, &p);
1970 encode_value (token, p, &p);
1972 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1973 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1979 compare_patches (gconstpointer a, gconstpointer b)
1983 i = (*(MonoJumpInfo**)a)->ip.i;
1984 j = (*(MonoJumpInfo**)b)->ip.i;
1998 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2001 static inline gboolean
2002 is_plt_patch (MonoJumpInfo *patch_info)
2004 switch (patch_info->type) {
2005 case MONO_PATCH_INFO_METHOD:
2006 case MONO_PATCH_INFO_INTERNAL_METHOD:
2007 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2008 case MONO_PATCH_INFO_CLASS_INIT:
2009 case MONO_PATCH_INFO_RGCTX_FETCH:
2010 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2011 case MONO_PATCH_INFO_MONITOR_ENTER:
2012 case MONO_PATCH_INFO_MONITOR_EXIT:
2020 * is_shared_got_patch:
2022 * Return whenever PATCH_INFO refers to a patch which needs a shared GOT
2024 * Keep it in sync with the version in aot-runtime.c.
2026 static inline gboolean
2027 is_shared_got_patch (MonoJumpInfo *patch_info)
2029 switch (patch_info->type) {
2030 case MONO_PATCH_INFO_VTABLE:
2031 case MONO_PATCH_INFO_CLASS:
2032 case MONO_PATCH_INFO_IID:
2033 case MONO_PATCH_INFO_ADJUSTED_IID:
2034 case MONO_PATCH_INFO_FIELD:
2035 case MONO_PATCH_INFO_SFLDA:
2036 case MONO_PATCH_INFO_DECLSEC:
2037 case MONO_PATCH_INFO_LDTOKEN:
2038 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2039 case MONO_PATCH_INFO_RVA:
2040 case MONO_PATCH_INFO_METHODCONST:
2048 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2052 if (is_plt_patch (patch_info)) {
2053 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
2058 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2060 res = acfg->plt_offset;
2061 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
2062 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
2063 acfg->plt_offset ++;
2073 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2074 * JI could be found if it exists, otherwise allocates a new one.
2077 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2081 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
2083 return got_offset - 1;
2085 got_offset = acfg->got_offset;
2086 acfg->got_offset ++;
2088 acfg->stats.got_slots ++;
2089 acfg->stats.got_slot_types [ji->type] ++;
2095 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2100 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
2101 got_offset = get_got_offset (acfg, ji);
2102 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
2103 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
2104 g_ptr_array_add (acfg->shared_patches, copy);
2107 return get_got_offset (acfg, ji);
2110 /* Add a method to the list of methods which need to be emitted */
2112 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
2114 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2115 g_ptr_array_add (acfg->methods, method);
2116 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2117 acfg->nmethods = acfg->methods->len + 1;
2122 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2124 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2132 add_method (MonoAotCompile *acfg, MonoMethod *method)
2136 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2140 index = acfg->method_index;
2141 add_method_with_index (acfg, method, index);
2143 /* FIXME: Fix quadratic behavior */
2144 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2146 acfg->method_index ++;
2152 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2156 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2159 add_method (acfg, method);
2160 g_ptr_array_add (acfg->extra_methods, method);
2164 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2166 MonoAotCompile *acfg = user_data;
2167 MonoJitICallInfo *callinfo = value;
2168 MonoMethod *wrapper;
2174 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2175 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2178 add_method (acfg, wrapper);
2182 get_runtime_invoke_sig (MonoMethodSignature *sig)
2184 MonoMethodBuilder *mb;
2187 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2188 m = mono_mb_create_method (mb, sig, 16);
2189 return mono_marshal_get_runtime_invoke (m);
2193 add_wrappers (MonoAotCompile *acfg)
2195 MonoMethod *method, *m;
2196 int i, j, nallocators;
2197 MonoMethodSignature *sig, *csig;
2201 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2202 * so there is only one wrapper of a given type, or inlining their contents into their
2207 * FIXME: This depends on the fact that different wrappers have different
2211 /* FIXME: Collect these automatically */
2213 /* Runtime invoke wrappers */
2215 /* void runtime-invoke () [.cctor] */
2216 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2217 csig->ret = &mono_defaults.void_class->byval_arg;
2218 add_method (acfg, get_runtime_invoke_sig (csig));
2220 /* void runtime-invoke () [Finalize] */
2221 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2223 csig->ret = &mono_defaults.void_class->byval_arg;
2224 add_method (acfg, get_runtime_invoke_sig (csig));
2226 /* void runtime-invoke (string) [exception ctor] */
2227 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2229 csig->ret = &mono_defaults.void_class->byval_arg;
2230 csig->params [0] = &mono_defaults.string_class->byval_arg;
2231 add_method (acfg, get_runtime_invoke_sig (csig));
2233 /* void runtime-invoke (string, string) [exception ctor] */
2234 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2236 csig->ret = &mono_defaults.void_class->byval_arg;
2237 csig->params [0] = &mono_defaults.string_class->byval_arg;
2238 csig->params [1] = &mono_defaults.string_class->byval_arg;
2239 add_method (acfg, get_runtime_invoke_sig (csig));
2241 /* string runtime-invoke () [Exception.ToString ()] */
2242 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2244 csig->ret = &mono_defaults.string_class->byval_arg;
2245 add_method (acfg, get_runtime_invoke_sig (csig));
2247 /* void runtime-invoke (string, Exception) [exception ctor] */
2248 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2250 csig->ret = &mono_defaults.void_class->byval_arg;
2251 csig->params [0] = &mono_defaults.string_class->byval_arg;
2252 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2253 add_method (acfg, get_runtime_invoke_sig (csig));
2255 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2256 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2258 csig->ret = &(mono_class_from_name (
2259 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2260 csig->params [0] = &mono_defaults.string_class->byval_arg;
2261 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2262 add_method (acfg, get_runtime_invoke_sig (csig));
2264 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2266 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2267 gboolean skip = FALSE;
2269 method = mono_get_method (acfg->image, token, NULL);
2271 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2272 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2273 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2276 if (method->is_generic || method->klass->generic_container)
2279 /* Skip methods which can not be handled by get_runtime_invoke () */
2280 sig = mono_method_signature (method);
2281 if ((sig->ret->type == MONO_TYPE_PTR) ||
2282 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2285 for (j = 0; j < sig->param_count; j++) {
2286 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2291 add_method (acfg, mono_marshal_get_runtime_invoke (method));
2294 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2295 MonoMethodDesc *desc;
2296 MonoMethod *orig_method;
2298 /* JIT icall wrappers */
2299 /* FIXME: locking */
2300 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2302 /* Managed Allocators */
2303 nallocators = mono_gc_get_managed_allocator_types ();
2304 for (i = 0; i < nallocators; ++i) {
2305 m = mono_gc_get_managed_allocator_by_type (i);
2307 add_method (acfg, m);
2311 add_method (acfg, mono_marshal_get_stelemref ());
2313 /* Monitor Enter/Exit */
2314 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2315 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2316 g_assert (orig_method);
2317 mono_method_desc_free (desc);
2318 add_method (acfg, mono_monitor_get_fast_path (orig_method));
2320 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2321 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2322 g_assert (orig_method);
2323 mono_method_desc_free (desc);
2324 add_method (acfg, mono_monitor_get_fast_path (orig_method));
2327 /* remoting-invoke wrappers */
2328 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2329 MonoMethodSignature *sig;
2331 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2332 method = mono_get_method (acfg->image, token, NULL);
2334 sig = mono_method_signature (method);
2336 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
2337 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2338 m = mono_marshal_get_remoting_invoke_with_check (method);
2340 add_method (acfg, m);
2344 /* delegate-invoke wrappers */
2345 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2348 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2349 klass = mono_class_get (acfg->image, token);
2351 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2352 method = mono_get_delegate_invoke (klass);
2354 m = mono_marshal_get_delegate_invoke (method, NULL);
2356 add_method (acfg, m);
2361 /* static rgctx wrappers */
2362 /* FIXME: Each wrapper belongs to a given instantiation of a generic method */
2363 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2364 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2365 method = mono_get_method (acfg->image, token, NULL);
2367 if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
2368 (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
2369 mono_class_generic_sharing_enabled (method->klass) &&
2370 mono_method_is_generic_sharable_impl (method, FALSE)) {
2371 m = mono_marshal_get_static_rgctx_invoke (method);
2372 add_method (acfg, m);
2379 has_type_vars (MonoClass *klass)
2381 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2384 return has_type_vars (klass->element_class);
2385 if (klass->generic_class) {
2386 MonoGenericContext *context = &klass->generic_class->context;
2387 if (context->class_inst) {
2390 for (i = 0; i < context->class_inst->type_argc; ++i)
2391 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2399 method_has_type_vars (MonoMethod *method)
2401 if (has_type_vars (method->klass))
2404 if (method->is_inflated) {
2405 MonoGenericContext *context = mono_method_get_context (method);
2406 if (context->method_inst) {
2409 for (i = 0; i < context->method_inst->type_argc; ++i)
2410 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2418 * add_generic_instances:
2420 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2423 add_generic_instances (MonoAotCompile *acfg)
2428 MonoGenericContext *context;
2430 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2431 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2432 method = mono_get_method (acfg->image, token, NULL);
2434 context = mono_method_get_context (method);
2435 if (context && ((context->class_inst && context->class_inst->is_open) ||
2436 (context->method_inst && context->method_inst->is_open)))
2439 if (method->klass->image != acfg->image)
2442 if (mono_method_is_generic_sharable_impl (method, FALSE))
2446 add_extra_method (acfg, method);
2449 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2453 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2455 klass = mono_class_get (acfg->image, token);
2458 mono_class_init (klass);
2460 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2463 if (has_type_vars (klass))
2467 * Add rgctx wrappers for cctors since those are called by the runtime, so
2468 * there is no methodspec for them. This is needed even for shared classes,
2469 * since rgctx wrappers belong to inflated methods.
2471 method = mono_class_get_cctor (klass);
2473 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
2476 while ((method = mono_class_get_methods (klass, &iter))) {
2477 if (mono_method_is_generic_sharable_impl (method, FALSE))
2481 if (method->is_generic)
2486 * FIXME: Instances which are referenced by these methods are not added,
2487 * for example Array.Resize<int> for List<int>.Add ().
2489 add_extra_method (acfg, method);
2495 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2497 int i, pindex, start_index, method_index;
2499 MonoJumpInfo *patch_info;
2500 MonoMethodHeader *header;
2501 gboolean skip, direct_call;
2503 char direct_call_target [128];
2506 header = mono_method_get_header (method);
2508 method_index = get_method_index (acfg, method);
2511 /* Collect and sort relocations */
2512 patches = g_ptr_array_new ();
2513 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2514 g_ptr_array_add (patches, patch_info);
2515 g_ptr_array_sort (patches, compare_patches);
2518 for (i = 0; i < code_len; i++) {
2520 for (pindex = start_index; pindex < patches->len; ++pindex) {
2521 patch_info = g_ptr_array_index (patches, pindex);
2522 if (patch_info->ip.i >= i)
2526 #ifdef MONO_ARCH_AOT_SUPPORTED
2528 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2529 start_index = pindex;
2531 switch (patch_info->type) {
2532 case MONO_PATCH_INFO_NONE:
2534 case MONO_PATCH_INFO_GOT_OFFSET: {
2535 guint32 offset = mono_arch_get_patch_offset (code + i);
2536 emit_bytes (acfg, code + i, offset);
2537 emit_symbol_diff (acfg, "got", ".", offset);
2539 i += offset + 4 - 1;
2544 if (!is_got_patch (patch_info->type))
2548 * If this patch is a call, try emitting a direct call instead of
2549 * through a PLT entry. This is possible if the called method is in
2550 * the same assembly and requires no initialization.
2552 direct_call = FALSE;
2553 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
2554 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2556 gboolean direct_callable = TRUE;
2558 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2559 direct_callable = FALSE;
2560 if (direct_callable) {
2561 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2563 sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
2564 patch_info->type = MONO_PATCH_INFO_NONE;
2565 acfg->stats.direct_calls ++;
2569 acfg->stats.all_calls ++;
2572 if (!got_only && !direct_call) {
2573 int plt_offset = get_plt_offset (acfg, patch_info);
2574 if (plt_offset != -1) {
2575 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2577 sprintf (direct_call_target, ".Lp_%d", plt_offset);
2579 /* Nullify the patch */
2580 patch_info->type = MONO_PATCH_INFO_NONE;
2585 #if defined(__i386__) || defined(__x86_64__)
2586 g_assert (code [i] == 0xe8);
2587 /* Need to make sure this is exactly 5 bytes long */
2588 emit_byte (acfg, '\xe8');
2589 emit_symbol_diff (acfg, direct_call_target, ".", -4);
2591 #elif defined(__arm__)
2592 #ifdef USE_BIN_WRITER
2593 /* FIXME: Can't encode this using the current symbol writer functions */
2594 g_assert_not_reached ();
2596 emit_unset_mode (acfg);
2597 fprintf (acfg->fp, "bl %s\n", direct_call_target);
2602 got_slot = get_got_offset (acfg, patch_info);
2604 emit_bytes (acfg, code + i, mono_arch_get_patch_offset (code + i));
2606 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
2607 #elif defined(__i386__)
2608 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
2609 #elif defined(__arm__)
2610 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
2612 g_assert_not_reached ();
2615 i += mono_arch_get_patch_offset (code + i) + 4 - 1;
2621 #endif /* MONO_ARCH_AOT_SUPPORTED */
2624 /* Find next patch */
2626 for (pindex = start_index; pindex < patches->len; ++pindex) {
2627 patch_info = g_ptr_array_index (patches, pindex);
2628 if (patch_info->ip.i >= i)
2632 /* Try to emit multiple bytes at once */
2633 if (pindex < patches->len && patch_info->ip.i > i) {
2634 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2635 i = patch_info->ip.i - 1;
2637 emit_bytes (acfg, code + i, 1);
2644 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2650 int func_alignment = 16;
2651 MonoMethodHeader *header;
2653 method = cfg->orig_method;
2654 code = cfg->native_code;
2655 header = mono_method_get_header (method);
2657 method_index = get_method_index (acfg, method);
2659 /* Make the labels local */
2660 sprintf (symbol, ".Lm_%x", method_index);
2662 emit_alignment (acfg, func_alignment);
2663 emit_label (acfg, symbol);
2664 if (acfg->aot_opts.write_symbols)
2665 emit_global (acfg, symbol, TRUE);
2667 if (cfg->verbose_level > 0)
2668 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2670 acfg->stats.code_size += cfg->code_len;
2672 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2674 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2682 * Encode PATCH_INFO into its disk representation.
2685 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2689 switch (patch_info->type) {
2690 case MONO_PATCH_INFO_NONE:
2692 case MONO_PATCH_INFO_IMAGE:
2693 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2695 case MONO_PATCH_INFO_METHOD_REL:
2696 encode_value ((gint)patch_info->data.offset, p, &p);
2698 case MONO_PATCH_INFO_SWITCH: {
2699 gpointer *table = (gpointer *)patch_info->data.table->table;
2702 encode_value (patch_info->data.table->table_size, p, &p);
2703 for (k = 0; k < patch_info->data.table->table_size; k++)
2704 encode_value ((int)(gssize)table [k], p, &p);
2707 case MONO_PATCH_INFO_METHODCONST:
2708 case MONO_PATCH_INFO_METHOD:
2709 case MONO_PATCH_INFO_METHOD_JUMP:
2710 case MONO_PATCH_INFO_ICALL_ADDR:
2711 case MONO_PATCH_INFO_METHOD_RGCTX:
2712 encode_method_ref (acfg, patch_info->data.method, p, &p);
2714 case MONO_PATCH_INFO_INTERNAL_METHOD:
2715 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2716 guint32 len = strlen (patch_info->data.name);
2718 encode_value (len, p, &p);
2720 memcpy (p, patch_info->data.name, len);
2725 case MONO_PATCH_INFO_LDSTR: {
2726 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2727 guint32 token = patch_info->data.token->token;
2728 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2729 encode_value (image_index, p, &p);
2730 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2733 case MONO_PATCH_INFO_RVA:
2734 case MONO_PATCH_INFO_DECLSEC:
2735 case MONO_PATCH_INFO_LDTOKEN:
2736 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2737 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2738 encode_value (patch_info->data.token->token, p, &p);
2739 encode_value (patch_info->data.token->has_context, p, &p);
2740 if (patch_info->data.token->has_context)
2741 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2743 case MONO_PATCH_INFO_EXC_NAME: {
2744 MonoClass *ex_class;
2747 mono_class_from_name (mono_defaults.exception_class->image,
2748 "System", patch_info->data.target);
2749 g_assert (ex_class);
2750 encode_klass_ref (acfg, ex_class, p, &p);
2753 case MONO_PATCH_INFO_R4:
2754 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2756 case MONO_PATCH_INFO_R8:
2757 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2758 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2760 case MONO_PATCH_INFO_VTABLE:
2761 case MONO_PATCH_INFO_CLASS:
2762 case MONO_PATCH_INFO_IID:
2763 case MONO_PATCH_INFO_ADJUSTED_IID:
2764 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2766 case MONO_PATCH_INFO_CLASS_INIT:
2767 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2768 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2770 case MONO_PATCH_INFO_FIELD:
2771 case MONO_PATCH_INFO_SFLDA:
2772 encode_field_info (acfg, patch_info->data.field, p, &p);
2774 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2776 case MONO_PATCH_INFO_RGCTX_FETCH: {
2777 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2779 encode_method_ref (acfg, entry->method, p, &p);
2780 encode_value (entry->in_mrgctx, p, &p);
2781 encode_value (entry->info_type, p, &p);
2782 encode_value (entry->data->type, p, &p);
2783 encode_patch (acfg, entry->data, p, &p);
2786 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2787 case MONO_PATCH_INFO_MONITOR_ENTER:
2788 case MONO_PATCH_INFO_MONITOR_EXIT:
2791 g_warning ("unable to handle jump info %d", patch_info->type);
2792 g_assert_not_reached ();
2799 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2802 guint32 last_offset, j, pindex;
2803 MonoJumpInfo *patch_info;
2805 encode_value (n_patches, p, &p);
2808 encode_value (first_got_offset, p, &p);
2810 /* First encode the type+position table */
2813 for (pindex = 0; pindex < patches->len; ++pindex) {
2815 patch_info = g_ptr_array_index (patches, pindex);
2817 if (patch_info->type == MONO_PATCH_INFO_NONE)
2822 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
2823 offset = patch_info->ip.i - last_offset;
2824 last_offset = patch_info->ip.i;
2826 /* Only the type is needed */
2827 *p = patch_info->type;
2831 /* Then encode the other info */
2832 for (pindex = 0; pindex < patches->len; ++pindex) {
2833 patch_info = g_ptr_array_index (patches, pindex);
2835 if (is_shared_got_patch (patch_info)) {
2836 guint32 offset = get_got_offset (acfg, patch_info);
2837 encode_value (offset, p, &p);
2839 encode_patch (acfg, patch_info, p, &p);
2847 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2851 int pindex, buf_size, n_patches;
2855 MonoJumpInfo *patch_info;
2856 MonoMethodHeader *header;
2857 guint32 method_index;
2859 guint32 first_got_offset;
2861 method = cfg->orig_method;
2862 code = cfg->native_code;
2863 header = mono_method_get_header (method);
2865 method_index = get_method_index (acfg, method);
2867 /* Make the labels local */
2868 sprintf (symbol, ".Lm_%x_p", method_index);
2870 /* Sort relocations */
2871 patches = g_ptr_array_new ();
2872 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2873 g_ptr_array_add (patches, patch_info);
2874 g_ptr_array_sort (patches, compare_patches);
2876 first_got_offset = acfg->cfgs [method_index]->got_offset;
2878 /**********************/
2879 /* Encode method info */
2880 /**********************/
2882 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2883 p = buf = g_malloc (buf_size);
2885 if (mono_class_get_cctor (method->klass))
2886 encode_klass_ref (acfg, method->klass, p, &p);
2888 /* Not needed when loading the method */
2889 encode_value (0, p, &p);
2892 if (cfg->opt & MONO_OPT_SHARED) {
2893 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2894 for (l = cfg->ldstr_list; l; l = l->next) {
2895 encode_value ((long)l->data, p, &p);
2899 /* Used only in shared mode */
2900 g_assert (!cfg->ldstr_list);
2903 for (pindex = 0; pindex < patches->len; ++pindex) {
2904 patch_info = g_ptr_array_index (patches, pindex);
2906 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2907 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2908 patch_info->type = MONO_PATCH_INFO_NONE;
2913 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2914 /* Stored in a GOT slot initialized at module load time */
2915 patch_info->type = MONO_PATCH_INFO_NONE;
2919 if (is_plt_patch (patch_info)) {
2920 /* Calls are made through the PLT */
2921 patch_info->type = MONO_PATCH_INFO_NONE;
2929 g_assert (cfg->has_got_slots);
2931 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2933 acfg->stats.info_size += p - buf;
2935 /* Emit method info */
2937 emit_label (acfg, symbol);
2939 g_assert (p - buf < buf_size);
2940 emit_bytes (acfg, buf, p - buf);
2945 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2948 int k, buf_size, method_index;
2949 guint32 debug_info_size;
2952 MonoMethodHeader *header;
2953 guint8 *p, *buf, *debug_info;
2954 MonoJitInfo *jinfo = cfg->jit_info;
2956 method = cfg->orig_method;
2957 code = cfg->native_code;
2958 header = mono_method_get_header (method);
2960 method_index = get_method_index (acfg, method);
2962 /* Make the labels local */
2963 sprintf (symbol, ".Le_%x_p", method_index);
2965 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2967 buf_size = header->num_clauses * 256 + debug_info_size + 128;
2968 p = buf = g_malloc (buf_size);
2970 encode_value (jinfo->code_size, p, &p);
2971 encode_value (jinfo->used_regs, p, &p);
2972 encode_value (jinfo->has_generic_jit_info, p, &p);
2974 /* Exception table */
2975 if (header->num_clauses) {
2976 for (k = 0; k < header->num_clauses; ++k) {
2977 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2979 encode_value (ei->exvar_offset, p, &p);
2981 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2982 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2984 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2985 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2986 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2990 if (jinfo->has_generic_jit_info) {
2991 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2993 encode_value (gi->has_this ? 1 : 0, p, &p);
2994 encode_value (gi->this_reg, p, &p);
2995 encode_value (gi->this_offset, p, &p);
2998 * Need to encode jinfo->method too, since it is not equal to 'method'
2999 * when using generic sharing.
3001 encode_method_ref (acfg, jinfo->method, p, &p);
3004 g_assert (debug_info_size < buf_size);
3006 encode_value (debug_info_size, p, &p);
3007 if (debug_info_size) {
3008 memcpy (p, debug_info, debug_info_size);
3009 p += debug_info_size;
3010 g_free (debug_info);
3013 acfg->stats.ex_info_size += p - buf;
3017 emit_label (acfg, symbol);
3019 g_assert (p - buf < buf_size);
3020 emit_bytes (acfg, buf, p - buf);
3025 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3027 MonoClass *klass = mono_class_get (acfg->image, token);
3031 gboolean no_special_static, cant_encode;
3032 gpointer iter = NULL;
3034 buf_size = 10240 + (klass->vtable_size * 16);
3035 p = buf = g_malloc (buf_size);
3039 mono_class_init (klass);
3041 mono_class_get_nested_types (klass, &iter);
3042 g_assert (klass->nested_classes_inited);
3044 mono_class_setup_vtable (klass);
3047 * Emit all the information which is required for creating vtables so
3048 * the runtime does not need to create the MonoMethod structures which
3049 * take up a lot of space.
3052 no_special_static = !mono_class_has_special_static_fields (klass);
3054 /* Check whenever we have enough info to encode the vtable */
3055 cant_encode = FALSE;
3056 for (i = 0; i < klass->vtable_size; ++i) {
3057 MonoMethod *cm = klass->vtable [i];
3059 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3063 if (klass->generic_container || cant_encode) {
3064 encode_value (-1, p, &p);
3066 encode_value (klass->vtable_size, p, &p);
3067 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);
3068 if (klass->has_cctor)
3069 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3070 if (klass->has_finalize)
3071 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3073 encode_value (klass->instance_size, p, &p);
3074 encode_value (mono_class_data_size (klass), p, &p);
3075 encode_value (klass->packing_size, p, &p);
3076 encode_value (klass->min_align, p, &p);
3078 for (i = 0; i < klass->vtable_size; ++i) {
3079 MonoMethod *cm = klass->vtable [i];
3082 encode_method_ref (acfg, cm, p, &p);
3084 encode_value (0, p, &p);
3088 acfg->stats.class_info_size += p - buf;
3091 sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
3092 emit_label (acfg, symbol);
3094 g_assert (p - buf < buf_size);
3095 emit_bytes (acfg, buf, p - buf);
3100 * Calls made from AOTed code are routed through a table of jumps similar to the
3101 * ELF PLT (Program Linkage Table). The differences are the following:
3102 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3103 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3104 * jumps. This means the jumps need to be patched when the address of the callee is
3105 * known. Initially the PLT entries jump to code which transfers control to the
3106 * AOT runtime through the first PLT entry.
3109 emit_plt (MonoAotCompile *acfg)
3114 guint32 *plt_info_offsets;
3117 * Encode info need to resolve PLT entries.
3119 buf_size = acfg->plt_offset * 128;
3120 p = buf = g_malloc (buf_size);
3122 plt_info_offsets = g_new0 (guint32, acfg->plt_offset);
3124 for (i = 1; i < acfg->plt_offset; ++i) {
3125 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3127 plt_info_offsets [i] = p - buf;
3128 encode_value (patch_info->type, p, &p);
3129 encode_patch (acfg, patch_info, p, &p);
3133 sprintf (symbol, "plt");
3135 emit_section_change (acfg, ".text", 0);
3136 emit_global (acfg, symbol, TRUE);
3138 /* This section will be made read-write by the AOT loader */
3139 emit_alignment (acfg, PAGESIZE);
3141 emit_label (acfg, symbol);
3143 #if defined(USE_BIN_WRITER) && defined(__arm__)
3145 g_assert_not_reached ();
3148 for (i = 0; i < acfg->plt_offset; ++i) {
3151 sprintf (label, ".Lp_%d", i);
3152 emit_label (acfg, label);
3155 * The first plt entry is used to transfer code to the AOT loader.
3158 #if defined(__i386__)
3160 /* It is filled up during loading by the AOT loader. */
3161 emit_zero_bytes (acfg, 16);
3163 /* Need to make sure this is 9 bytes long */
3164 emit_byte (acfg, '\xe9');
3165 emit_symbol_diff (acfg, "plt", ".", -4);
3166 emit_int32 (acfg, plt_info_offsets [i]);
3168 #elif defined(__x86_64__)
3170 * We can't emit jumps because they are 32 bits only so they can't be patched.
3171 * So we emit a jump table instead whose entries are patched by the AOT loader to
3172 * point to .Lpd entries. ELF stores these in the GOT too, but we don't, since
3173 * methods with GOT entries can't be called directly.
3174 * We also emit the default PLT code here since the PLT code will not be patched.
3175 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
3177 /* jmpq *<offset>(%rip) */
3178 emit_byte (acfg, '\xff');
3179 emit_byte (acfg, '\x25');
3180 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)) -4);
3181 /* Used by mono_aot_get_plt_info_offset */
3182 emit_int32 (acfg, plt_info_offsets [i]);
3183 #elif defined(__arm__)
3185 * - optimize OP_AOTCONST implementation
3186 * - optimize the PLT entries
3187 * - optimize SWITCH AOT implementation
3188 * - implement IMT support
3190 emit_unset_mode (acfg);
3191 fprintf (acfg->fp, "\tldr ip, [pc, #4]\n");
3192 fprintf (acfg->fp, "\tadd ip, pc, ip\n");
3193 fprintf (acfg->fp, "\tldr pc, [ip, #0]\n");
3194 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)));
3195 /* Used by mono_aot_get_plt_info_offset */
3196 #if defined(__MACH__)
3197 fprintf (acfg->fp, "\n\t.long %d\n", plt_info_offsets [i]);
3199 fprintf (acfg->fp, "\n\t.word %d\n", plt_info_offsets [i]);
3203 g_assert_not_reached ();
3207 g_free (plt_info_offsets);
3209 sprintf (symbol, "plt_end");
3210 emit_global (acfg, symbol, TRUE);
3211 emit_label (acfg, symbol);
3214 sprintf (symbol, "plt_info");
3215 emit_global (acfg, symbol, FALSE);
3216 emit_label (acfg, symbol);
3218 g_assert (p - buf < buf_size);
3219 emit_bytes (acfg, buf, p - buf);
3222 sprintf (symbol, "plt_jump_table_addr");
3223 emit_section_change (acfg, ".data", 0);
3224 emit_global (acfg, symbol, FALSE);
3225 emit_alignment (acfg, 8);
3226 emit_label (acfg, symbol);
3227 emit_pointer (acfg, "plt_jump_table");
3229 sprintf (symbol, "plt_jump_table_size");
3230 emit_section_change (acfg, ".data", 0);
3231 emit_global (acfg, symbol, FALSE);
3232 emit_alignment (acfg, 8);
3233 emit_label (acfg, symbol);
3234 emit_symbol_diff (acfg, "plt_jump_table_end", "plt_jump_table", 0);
3236 /* Don't make this a global so accesses don't need relocations */
3237 sprintf (symbol, "plt_jump_table");
3238 emit_section_change (acfg, ".bss", 0);
3239 emit_label (acfg, symbol);
3241 #if defined(__x86_64__) || defined(__arm__)
3242 emit_zero_bytes (acfg, (int)(acfg->plt_offset * sizeof (gpointer)));
3245 sprintf (symbol, "plt_jump_table_end");
3246 emit_label (acfg, symbol);
3249 static G_GNUC_UNUSED void
3250 emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code,
3251 guint32 code_size, int got_offset, MonoJumpInfo *ji)
3255 MonoJumpInfo *patch_info;
3261 sprintf (symbol, "%s", name);
3263 emit_section_change (acfg, ".text", 0);
3264 emit_global (acfg, symbol, TRUE);
3265 emit_alignment (acfg, 16);
3266 emit_label (acfg, symbol);
3269 * The code should access everything through the GOT, so we pass
3272 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3276 /* Sort relocations */
3277 patches = g_ptr_array_new ();
3278 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3279 g_ptr_array_add (patches, patch_info);
3280 g_ptr_array_sort (patches, compare_patches);
3282 buf_size = patches->len * 128 + 128;
3283 buf = g_malloc (buf_size);
3286 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3287 g_assert (p - buf < buf_size);
3289 sprintf (symbol, "%s_p", name);
3291 emit_section_change (acfg, ".text", 0);
3292 emit_global (acfg, symbol, FALSE);
3293 emit_label (acfg, symbol);
3295 emit_bytes (acfg, buf, p - buf);
3299 * When running in aot-only mode, we can't create trampolines at runtime, so we create
3300 * a few, and save them in the AOT file. Normal trampolines embed their argument as a
3301 * literal inside the trampoline code, we can't do that here, so instead we embed an offset
3302 * which needs to be added to the trampoline address to get the address of the GOT slot
3303 * which contains the argument value.
3304 * The generated trampolines jump to the generic trampolines using another GOT slot, which
3305 * will be setup by the AOT loader to point to the generic trampoline code of the given
3309 emit_trampolines (MonoAotCompile *acfg)
3313 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3320 if (!acfg->aot_opts.full_aot)
3323 g_assert (acfg->image->assembly);
3325 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3326 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3327 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3329 * Emit the generic trampolines.
3331 * We could save some code by treating the generic trampolines as a wrapper
3332 * method, but that approach has its own complexities, so we choose the simpler
3335 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3336 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, TRUE);
3338 /* Emit trampoline code */
3340 sprintf (symbol, "generic_trampoline_%d", tramp_type);
3342 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3345 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3346 emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL);
3348 /* Emit the exception related code pieces */
3349 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3350 emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji);
3351 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3352 emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji);
3353 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3354 emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji);
3355 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3356 emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji);
3357 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3358 emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji);
3359 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3360 emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji);
3363 for (i = 0; i < 128; ++i) {
3366 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3367 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3368 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3369 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3371 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3372 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3373 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3374 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3380 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3384 /* Reserve some entries at the end of the GOT for our use */
3385 acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
3387 sprintf (symbol, "trampolines");
3389 emit_section_change (acfg, ".text", 0);
3390 emit_global (acfg, symbol, TRUE);
3391 emit_alignment (acfg, 16);
3392 emit_label (acfg, symbol);
3394 for (i = 0; i < acfg->num_aot_trampolines; ++i) {
3395 offset = acfg->got_offset + (i * 2);
3398 * The trampolines created here are variations of the specific
3399 * trampolines created in mono_arch_create_specific_trampoline (). The
3401 * - the generic trampoline address is taken from a got slot.
3402 * - the offset of the got slot where the trampoline argument is stored
3403 * is embedded in the instruction stream, and the generic trampoline
3404 * can load the argument by loading the offset, adding it to the
3405 * address of the trampoline to get the address of the got slot, and
3406 * loading the argument from the there.
3408 #if defined(__x86_64__)
3409 /* This should be exactly 16 bytes long */
3410 /* It should work together with the generic trampoline code in tramp-amd64.c */
3411 /* call *<offset>(%rip) */
3412 emit_byte (acfg, '\x41');
3413 emit_byte (acfg, '\xff');
3414 emit_byte (acfg, '\x15');
3415 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
3416 /* This should be relative to the start of the trampoline */
3417 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
3418 emit_zero_bytes (acfg, 5);
3419 #elif defined(__arm__)
3423 /* Generate the trampoline code */
3424 /* This should be exactly 28 bytes long */
3427 ARM_PUSH (code, 0x5fff);
3428 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
3429 /* Load the value from the GOT */
3430 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
3432 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
3433 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
3435 g_assert (code - buf == 20);
3438 emit_bytes (acfg, buf, code - buf);
3439 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
3440 emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
3443 g_assert_not_reached ();
3448 /* Unbox trampolines */
3450 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3452 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3454 char call_target [256];
3456 method = mono_get_method (acfg->image, token, NULL);
3458 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3459 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
3462 sprintf (symbol, "unbox_trampoline_%d", i);
3464 emit_section_change (acfg, ".text", 0);
3465 emit_global (acfg, symbol, TRUE);
3466 emit_label (acfg, symbol);
3468 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
3470 #if defined(__x86_64__)
3475 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (cfg->orig_method), cfg->generic_sharing_context, NULL);
3477 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
3479 emit_bytes (acfg, buf, code - buf);
3481 emit_byte (acfg, '\xe9');
3482 emit_symbol_diff (acfg, call_target, ".", -4);
3484 #elif defined(__arm__)
3491 if (MONO_TYPE_ISSTRUCT (mono_method_signature (cfg->orig_method)->ret))
3494 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
3496 emit_bytes (acfg, buf, code - buf);
3497 /* jump to method */
3498 #if defined(USE_BIN_WRITER)
3500 g_assert_not_reached ();
3502 fprintf (acfg->fp, "\n\tb %s\n", call_target);
3505 g_assert_not_reached ();
3509 sprintf (symbol, "trampolines_info");
3511 emit_section_change (acfg, ".text", 0);
3512 emit_global (acfg, symbol, TRUE);
3513 emit_alignment (acfg, PAGESIZE);
3514 emit_label (acfg, symbol);
3516 emit_int32 (acfg, acfg->num_aot_trampolines);
3517 emit_int32 (acfg, acfg->got_offset);
3521 str_begins_with (const char *str1, const char *str2)
3523 int len = strlen (str2);
3524 return strncmp (str1, str2, len) == 0;
3528 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3530 gchar **args, **ptr;
3532 memset (opts, 0, sizeof (*opts));
3534 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3535 for (ptr = args; ptr && *ptr; ptr ++) {
3536 const char *arg = *ptr;
3538 if (str_begins_with (arg, "outfile=")) {
3539 opts->outfile = g_strdup (arg + strlen ("outfile="));
3540 } else if (str_begins_with (arg, "save-temps")) {
3541 opts->save_temps = TRUE;
3542 } else if (str_begins_with (arg, "keep-temps")) {
3543 opts->save_temps = TRUE;
3544 } else if (str_begins_with (arg, "write-symbols")) {
3545 opts->write_symbols = TRUE;
3546 } else if (str_begins_with (arg, "metadata-only")) {
3547 opts->metadata_only = TRUE;
3548 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3549 opts->bind_to_runtime_version = TRUE;
3550 } else if (str_begins_with (arg, "full")) {
3551 opts->full_aot = TRUE;
3553 * The no-dlsym option is only useful on the iphone, and even there,
3554 * do to other limitations of the dynamic linker, it doesn't seem to
3555 * work. So disable it for now so we don't have to support it.
3558 } else if (str_begins_with (arg, "no-dlsym")) {
3559 opts->no_dlsym = TRUE;
3561 } else if (str_begins_with (arg, "threads=")) {
3562 opts->nthreads = atoi (arg + strlen ("threads="));
3563 } else if (str_begins_with (arg, "static")) {
3564 opts->static_link = TRUE;
3565 opts->no_dlsym = TRUE;
3566 } else if (str_begins_with (arg, "asmonly")) {
3567 opts->asm_only = TRUE;
3569 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3578 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3580 MonoMethod *method = (MonoMethod*)key;
3581 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3582 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3583 MonoAotCompile *acfg = user_data;
3585 new_ji->image = ji->image;
3586 new_ji->token = ji->token;
3587 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3593 * AOT compile a given method.
3594 * This function might be called by multiple threads, so it must be thread-safe.
3597 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3600 MonoJumpInfo *patch_info;
3603 MonoMethod *wrapped;
3605 if (acfg->aot_opts.metadata_only)
3608 mono_acfg_lock (acfg);
3609 index = get_method_index (acfg, method);
3610 mono_acfg_unlock (acfg);
3612 /* fixme: maybe we can also precompile wrapper methods */
3613 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3614 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3615 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3616 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3620 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3623 wrapped = mono_marshal_method_from_wrapper (method);
3624 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3625 // FIXME: The wrapper should be generic too, but it is not
3628 InterlockedIncrement (&acfg->stats.mcount);
3630 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3632 * FIXME: Enabling this causes virtual-sync.exe to fail, since the trampoline
3633 * code can't determine that it needs to insert a sync wrapper in the AOT case.
3639 if (method->is_generic || method->klass->generic_container) {
3640 InterlockedIncrement (&acfg->stats.genericcount);
3645 if (acfg->aot_opts.full_aot)
3646 mono_use_imt = FALSE;
3649 * Since these methods are the only ones which are compiled with
3650 * AOT support, and they are not used by runtime startup/shutdown code,
3651 * the runtime will not see AOT methods during AOT compilation,so it
3652 * does not need to support them by creating a fake GOT etc.
3654 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3655 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3656 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3657 InterlockedIncrement (&acfg->stats.genericcount);
3660 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3661 /* Let the exception happen at runtime */
3665 if (cfg->disable_aot) {
3666 //printf ("Skip (other): %s\n", mono_method_full_name (method, TRUE));
3667 InterlockedIncrement (&acfg->stats.ocount);
3668 mono_destroy_compile (cfg);
3672 /* Nullify patches which need no aot processing */
3673 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3674 switch (patch_info->type) {
3675 case MONO_PATCH_INFO_LABEL:
3676 case MONO_PATCH_INFO_BB:
3677 patch_info->type = MONO_PATCH_INFO_NONE;
3684 /* Collect method->token associations from the cfg */
3685 mono_acfg_lock (acfg);
3686 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3687 mono_acfg_unlock (acfg);
3690 * Check for absolute addresses.
3693 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3694 switch (patch_info->type) {
3695 case MONO_PATCH_INFO_ABS:
3696 /* unable to handle this */
3697 //printf ("Skip (abs addr): %s %d\n", mono_method_full_name (method, TRUE), patch_info->type);
3706 InterlockedIncrement (&acfg->stats.abscount);
3707 mono_destroy_compile (cfg);
3712 * Check for wrapper methods we can't encode.
3715 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3716 if ((patch_info->type == MONO_PATCH_INFO_METHODCONST) || (patch_info->type == MONO_PATCH_INFO_METHOD)) {
3717 switch (patch_info->data.method->wrapper_type) {
3718 case MONO_WRAPPER_NONE:
3719 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3720 case MONO_WRAPPER_XDOMAIN_INVOKE:
3721 case MONO_WRAPPER_STFLD:
3722 case MONO_WRAPPER_LDFLD:
3723 case MONO_WRAPPER_LDFLDA:
3724 case MONO_WRAPPER_LDFLD_REMOTE:
3725 case MONO_WRAPPER_STFLD_REMOTE:
3726 case MONO_WRAPPER_STELEMREF:
3727 case MONO_WRAPPER_ISINST:
3728 case MONO_WRAPPER_PROXY_ISINST:
3729 case MONO_WRAPPER_ALLOC:
3730 case MONO_WRAPPER_REMOTING_INVOKE:
3731 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
3732 case MONO_WRAPPER_MONITOR_FAST_ENTER:
3733 case MONO_WRAPPER_MONITOR_FAST_EXIT:
3736 /* unable to handle this */
3737 //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));
3741 } else if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH) {
3742 MonoJumpInfo *child = patch_info->data.rgctx_entry->data;
3744 if (child->type == MONO_PATCH_INFO_METHODCONST) {
3745 switch (child->data.method->wrapper_type) {
3746 case MONO_WRAPPER_NONE:
3747 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
3757 InterlockedIncrement (&acfg->stats.wrappercount);
3758 mono_destroy_compile (cfg);
3762 /* Lock for the rest of the code */
3763 mono_acfg_lock (acfg);
3766 * Check for methods/klasses we can't encode.
3769 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3770 switch (patch_info->type) {
3771 case MONO_PATCH_INFO_METHOD:
3772 case MONO_PATCH_INFO_METHODCONST:
3773 if (patch_info->data.method->wrapper_type)
3775 if (!patch_info->data.method->token) {
3776 /* The method is part of a constructed type like Int[,].Set (). */
3777 if (!g_hash_table_lookup (acfg->token_info_hash, patch_info->data.method))
3781 case MONO_PATCH_INFO_VTABLE:
3782 case MONO_PATCH_INFO_CLASS_INIT:
3783 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3784 case MONO_PATCH_INFO_CLASS:
3785 case MONO_PATCH_INFO_IID:
3786 case MONO_PATCH_INFO_ADJUSTED_IID:
3787 if (!patch_info->data.klass->type_token)
3788 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))
3797 acfg->stats.ocount++;
3798 mono_destroy_compile (cfg);
3799 mono_acfg_unlock (acfg);
3803 /* Adds generic instances referenced by this method */
3804 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3805 switch (patch_info->type) {
3806 case MONO_PATCH_INFO_METHOD: {
3807 MonoMethod *m = patch_info->data.method;
3808 if (m->is_inflated) {
3809 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3810 mono_method_is_generic_sharable_impl (m, FALSE)) &&
3811 !method_has_type_vars (m))
3812 add_extra_method (acfg, m);
3821 /* Determine whenever the method has GOT slots */
3822 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3823 switch (patch_info->type) {
3824 case MONO_PATCH_INFO_GOT_OFFSET:
3825 case MONO_PATCH_INFO_NONE:
3827 case MONO_PATCH_INFO_IMAGE:
3828 /* The assembly is stored in GOT slot 0 */
3829 if (patch_info->data.image != acfg->image)
3830 cfg->has_got_slots = TRUE;
3833 if (!is_plt_patch (patch_info))
3834 cfg->has_got_slots = TRUE;
3839 if (!cfg->has_got_slots)
3840 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3842 /* Make a copy of the patch info which is in the mempool */
3844 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3846 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3847 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3850 patches = new_patch_info;
3852 patches_end->next = new_patch_info;
3853 patches_end = new_patch_info;
3855 cfg->patch_info = patches;
3858 /* Free some fields used by cfg to conserve memory */
3859 mono_mempool_destroy (cfg->mempool);
3860 cfg->mempool = NULL;
3861 g_free (cfg->varinfo);
3862 cfg->varinfo = NULL;
3866 mono_regstate_free (cfg->rs);
3870 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
3872 while (index >= acfg->cfgs_size) {
3873 MonoCompile **new_cfgs;
3876 new_size = acfg->cfgs_size * 2;
3877 new_cfgs = g_new0 (MonoCompile*, new_size);
3878 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3879 g_free (acfg->cfgs);
3880 acfg->cfgs = new_cfgs;
3881 acfg->cfgs_size = new_size;
3883 acfg->cfgs [index] = cfg;
3885 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3887 if (cfg->orig_method->wrapper_type)
3888 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3890 mono_acfg_unlock (acfg);
3892 InterlockedIncrement (&acfg->stats.ccount);
3896 compile_thread_main (gpointer *user_data)
3898 MonoDomain *domain = user_data [0];
3899 MonoAotCompile *acfg = user_data [1];
3900 GPtrArray *methods = user_data [2];
3903 mono_thread_attach (domain);
3905 for (i = 0; i < methods->len; ++i)
3906 compile_method (acfg, g_ptr_array_index (methods, i));
3910 load_profile_files (MonoAotCompile *acfg)
3914 int file_index, res, method_index, i;
3921 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);
3923 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3928 infile = fopen (tmp, "r");
3931 printf ("Using profile data file '%s'\n", tmp);
3936 res = fscanf (infile, "%32s\n", ver);
3937 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3938 printf ("Profile file has wrong version or invalid.\n");
3944 res = fscanf (infile, "%d\n", &token);
3948 method_index = mono_metadata_token_index (token) - 1;
3950 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3951 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3956 /* Add missing methods */
3958 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3959 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3960 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3962 unordered = g_list_reverse (unordered);
3963 if (acfg->method_order)
3964 g_list_last (acfg->method_order)->next = unordered;
3966 acfg->method_order = unordered;
3972 * Collect all patches which have shared GOT entries and alloc entries for them. The
3973 * rest will get entries allocated during emit_code ().
3976 alloc_got_slots (MonoAotCompile *acfg)
3982 /* Slot 0 is reserved for the address of the current assembly */
3983 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3984 ji->type = MONO_PATCH_INFO_IMAGE;
3985 ji->data.image = acfg->image;
3987 get_shared_got_offset (acfg, ji);
3989 for (l = acfg->method_order; l != NULL; l = l->next) {
3990 i = GPOINTER_TO_UINT (l->data);
3992 if (acfg->cfgs [i]) {
3993 MonoCompile *cfg = acfg->cfgs [i];
3995 for (ji = cfg->patch_info; ji; ji = ji->next) {
3996 if (is_shared_got_patch (ji))
3997 get_shared_got_offset (acfg, ji);
4004 emit_code (MonoAotCompile *acfg)
4010 sprintf (symbol, "methods");
4011 emit_section_change (acfg, ".text", 0);
4012 emit_global (acfg, symbol, TRUE);
4013 emit_alignment (acfg, 8);
4014 emit_label (acfg, symbol);
4016 for (l = acfg->method_order; l != NULL; l = l->next) {
4017 i = GPOINTER_TO_UINT (l->data);
4020 emit_method_code (acfg, acfg->cfgs [i]);
4023 sprintf (symbol, "methods_end");
4024 emit_section_change (acfg, ".text", 0);
4025 emit_global (acfg, symbol, FALSE);
4026 emit_alignment (acfg, 8);
4027 emit_label (acfg, symbol);
4029 sprintf (symbol, "method_offsets");
4030 emit_section_change (acfg, ".text", 1);
4031 emit_global (acfg, symbol, FALSE);
4032 emit_alignment (acfg, 8);
4033 emit_label (acfg, symbol);
4035 for (i = 0; i < acfg->nmethods; ++i) {
4036 if (acfg->cfgs [i]) {
4037 sprintf (symbol, ".Lm_%x", i);
4038 emit_symbol_diff (acfg, symbol, "methods", 0);
4040 emit_int32 (acfg, 0xffffffff);
4047 emit_info (MonoAotCompile *acfg)
4053 /* Emit method info */
4054 sprintf (symbol, "method_info");
4055 emit_section_change (acfg, ".text", 1);
4056 emit_global (acfg, symbol, FALSE);
4057 emit_alignment (acfg, 8);
4058 emit_label (acfg, symbol);
4060 /* To reduce size of generated assembly code */
4061 sprintf (symbol, "mi");
4062 emit_label (acfg, symbol);
4064 for (l = acfg->method_order; l != NULL; l = l->next) {
4065 i = GPOINTER_TO_UINT (l->data);
4068 emit_method_info (acfg, acfg->cfgs [i]);
4071 sprintf (symbol, "method_info_offsets");
4072 emit_section_change (acfg, ".text", 1);
4073 emit_global (acfg, symbol, FALSE);
4074 emit_alignment (acfg, 8);
4075 emit_label (acfg, symbol);
4077 for (i = 0; i < acfg->nmethods; ++i) {
4078 if (acfg->cfgs [i]) {
4079 sprintf (symbol, ".Lm_%x_p", i);
4080 emit_symbol_diff (acfg, symbol, "mi", 0);
4082 emit_int32 (acfg, 0);
4088 typedef struct HashEntry {
4089 guint32 key, value, index;
4090 struct HashEntry *next;
4094 * emit_extra_methods:
4096 * Emit methods which are not in the METHOD table, like wrappers.
4099 emit_extra_methods (MonoAotCompile *acfg)
4101 int i, table_size, buf_size;
4104 guint32 *info_offsets;
4107 HashEntry *entry, *new_entry;
4110 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4112 buf_size = acfg->extra_methods->len * 256 + 256;
4113 p = buf = g_malloc (buf_size);
4115 /* Encode method info */
4117 /* So offsets are > 0 */
4120 for (i = 0; i < acfg->extra_methods->len; ++i) {
4121 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4122 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4128 info_offsets [i] = p - buf;
4130 if (method->wrapper_type) {
4133 // FIXME: Optimize disk usage
4134 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
4135 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4136 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
4139 name = mono_method_full_name (cfg->orig_method, TRUE);
4142 encode_value (1, p, &p);
4143 strcpy ((char*)p, name);
4144 p += strlen (name ) + 1;
4147 encode_value (0, p, &p);
4148 encode_method_ref (acfg, method, p, &p);
4151 g_assert ((p - buf) < buf_size);
4154 g_assert ((p - buf) < buf_size);
4156 /* Emit method info */
4157 sprintf (symbol, "extra_method_info");
4158 emit_section_change (acfg, ".text", 1);
4159 emit_global (acfg, symbol, FALSE);
4160 emit_alignment (acfg, 8);
4161 emit_label (acfg, symbol);
4163 emit_bytes (acfg, buf, p - buf);
4168 * Construct a chained hash table for mapping indexes in extra_method_info to
4171 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4172 table = g_ptr_array_sized_new (table_size);
4173 for (i = 0; i < table_size; ++i)
4174 g_ptr_array_add (table, NULL);
4175 for (i = 0; i < acfg->extra_methods->len; ++i) {
4176 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4177 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4183 key = info_offsets [i];
4184 value = get_method_index (acfg, method);
4186 if (method->wrapper_type) {
4187 hash = g_str_hash (method->name) % table_size;
4190 hash = 0 % table_size;
4193 /* FIXME: Allocate from the mempool */
4194 new_entry = g_new0 (HashEntry, 1);
4195 new_entry->key = key;
4196 new_entry->value = value;
4198 entry = g_ptr_array_index (table, hash);
4199 if (entry == NULL) {
4200 new_entry->index = hash;
4201 g_ptr_array_index (table, hash) = new_entry;
4204 entry = entry->next;
4206 entry->next = new_entry;
4207 new_entry->index = table->len;
4208 g_ptr_array_add (table, new_entry);
4212 /* Emit the table */
4213 sprintf (symbol, "extra_method_table");
4214 emit_section_change (acfg, ".text", 0);
4215 emit_global (acfg, symbol, FALSE);
4216 emit_alignment (acfg, 8);
4217 emit_label (acfg, symbol);
4219 g_assert (table_size < 65000);
4220 emit_int32 (acfg, table_size);
4221 g_assert (table->len < 65000);
4222 for (i = 0; i < table->len; ++i) {
4223 HashEntry *entry = g_ptr_array_index (table, i);
4225 if (entry == NULL) {
4226 emit_int32 (acfg, 0);
4227 emit_int32 (acfg, 0);
4228 emit_int32 (acfg, 0);
4230 g_assert (entry->key > 0);
4231 emit_int32 (acfg, entry->key);
4232 emit_int32 (acfg, entry->value);
4234 emit_int32 (acfg, entry->next->index);
4236 emit_int32 (acfg, 0);
4241 * Emit a table reverse mapping method indexes to their index in extra_method_info.
4242 * This is used by mono_aot_find_jit_info ().
4244 sprintf (symbol, "extra_method_info_offsets");
4245 emit_section_change (acfg, ".text", 0);
4246 emit_global (acfg, symbol, FALSE);
4247 emit_alignment (acfg, 8);
4248 emit_label (acfg, symbol);
4250 emit_int32 (acfg, acfg->extra_methods->len);
4251 for (i = 0; i < acfg->extra_methods->len; ++i) {
4252 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4254 emit_int32 (acfg, get_method_index (acfg, method));
4255 emit_int32 (acfg, info_offsets [i]);
4260 emit_method_order (MonoAotCompile *acfg)
4266 sprintf (symbol, "method_order");
4267 emit_section_change (acfg, ".text", 1);
4268 emit_global (acfg, symbol, FALSE);
4269 emit_alignment (acfg, 8);
4270 emit_label (acfg, symbol);
4272 /* First emit an index table */
4275 for (l = acfg->method_order; l != NULL; l = l->next) {
4276 i = GPOINTER_TO_UINT (l->data);
4278 if (acfg->cfgs [i]) {
4279 if ((index % 1024) == 0) {
4280 emit_int32 (acfg, i);
4288 emit_int32 (acfg, 0xffffff);
4290 /* Then emit the whole method order */
4291 for (l = acfg->method_order; l != NULL; l = l->next) {
4292 i = GPOINTER_TO_UINT (l->data);
4294 if (acfg->cfgs [i]) {
4295 emit_int32 (acfg, i);
4300 sprintf (symbol, "method_order_end");
4301 emit_section_change (acfg, ".text", 1);
4302 emit_global (acfg, symbol, FALSE);
4303 emit_label (acfg, symbol);
4307 emit_exception_info (MonoAotCompile *acfg)
4312 sprintf (symbol, "ex_info");
4313 emit_section_change (acfg, ".text", 1);
4314 emit_global (acfg, symbol, FALSE);
4315 emit_alignment (acfg, 8);
4316 emit_label (acfg, symbol);
4318 /* To reduce size of generated assembly */
4319 sprintf (symbol, "ex");
4320 emit_label (acfg, symbol);
4322 for (i = 0; i < acfg->nmethods; ++i) {
4324 emit_exception_debug_info (acfg, acfg->cfgs [i]);
4327 sprintf (symbol, "ex_info_offsets");
4328 emit_section_change (acfg, ".text", 1);
4329 emit_global (acfg, symbol, FALSE);
4330 emit_alignment (acfg, 8);
4331 emit_label (acfg, symbol);
4333 for (i = 0; i < acfg->nmethods; ++i) {
4334 if (acfg->cfgs [i]) {
4335 sprintf (symbol, ".Le_%x_p", i);
4336 emit_symbol_diff (acfg, symbol, "ex", 0);
4338 emit_int32 (acfg, 0);
4345 emit_class_info (MonoAotCompile *acfg)
4350 sprintf (symbol, "class_info");
4351 emit_section_change (acfg, ".text", 1);
4352 emit_global (acfg, symbol, FALSE);
4353 emit_alignment (acfg, 8);
4354 emit_label (acfg, symbol);
4356 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4357 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4359 sprintf (symbol, "class_info_offsets");
4360 emit_section_change (acfg, ".text", 1);
4361 emit_global (acfg, symbol, FALSE);
4362 emit_alignment (acfg, 8);
4363 emit_label (acfg, symbol);
4365 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4366 sprintf (symbol, ".LK_I_%x", i);
4367 emit_symbol_diff (acfg, symbol, "class_info", 0);
4372 typedef struct ClassNameTableEntry {
4373 guint32 token, index;
4374 struct ClassNameTableEntry *next;
4375 } ClassNameTableEntry;
4378 emit_class_name_table (MonoAotCompile *acfg)
4381 guint32 token, hash;
4386 ClassNameTableEntry *entry, *new_entry;
4389 * Construct a chained hash table for mapping class names to typedef tokens.
4391 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4392 table = g_ptr_array_sized_new (table_size);
4393 for (i = 0; i < table_size; ++i)
4394 g_ptr_array_add (table, NULL);
4395 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4396 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4397 klass = mono_class_get (acfg->image, token);
4398 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4399 hash = g_str_hash (full_name) % table_size;
4402 /* FIXME: Allocate from the mempool */
4403 new_entry = g_new0 (ClassNameTableEntry, 1);
4404 new_entry->token = token;
4406 entry = g_ptr_array_index (table, hash);
4407 if (entry == NULL) {
4408 new_entry->index = hash;
4409 g_ptr_array_index (table, hash) = new_entry;
4412 entry = entry->next;
4414 entry->next = new_entry;
4415 new_entry->index = table->len;
4416 g_ptr_array_add (table, new_entry);
4420 /* Emit the table */
4421 sprintf (symbol, "class_name_table");
4422 emit_section_change (acfg, ".text", 0);
4423 emit_global (acfg, symbol, FALSE);
4424 emit_alignment (acfg, 8);
4425 emit_label (acfg, symbol);
4427 /* FIXME: Optimize memory usage */
4428 g_assert (table_size < 65000);
4429 emit_int16 (acfg, table_size);
4430 g_assert (table->len < 65000);
4431 for (i = 0; i < table->len; ++i) {
4432 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4434 if (entry == NULL) {
4435 emit_int16 (acfg, 0);
4436 emit_int16 (acfg, 0);
4438 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4440 emit_int16 (acfg, entry->next->index);
4442 emit_int16 (acfg, 0);
4448 emit_image_table (MonoAotCompile *acfg)
4454 * The image table is small but referenced in a lot of places.
4455 * So we emit it at once, and reference its elements by an index.
4458 sprintf (symbol, "mono_image_table");
4459 emit_section_change (acfg, ".text", 1);
4460 emit_global (acfg, symbol, FALSE);
4461 emit_alignment (acfg, 8);
4462 emit_label (acfg, symbol);
4464 emit_int32 (acfg, acfg->image_table->len);
4465 for (i = 0; i < acfg->image_table->len; i++) {
4466 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4467 MonoAssemblyName *aname = &image->assembly->aname;
4469 /* FIXME: Support multi-module assemblies */
4470 g_assert (image->assembly->image == image);
4472 emit_string (acfg, image->assembly_name);
4473 emit_string (acfg, image->guid);
4474 emit_string (acfg, aname->culture ? aname->culture : "");
4475 emit_string (acfg, (const char*)aname->public_key_token);
4477 emit_alignment (acfg, 8);
4478 emit_int32 (acfg, aname->flags);
4479 emit_int32 (acfg, aname->major);
4480 emit_int32 (acfg, aname->minor);
4481 emit_int32 (acfg, aname->build);
4482 emit_int32 (acfg, aname->revision);
4487 emit_got_info (MonoAotCompile *acfg)
4492 guint32 *got_info_offsets;
4496 * - optimize offsets table.
4497 * - reduce number of exported symbols.
4498 * - emit info for a klass only once.
4499 * - determine when a method uses a GOT slot which is guaranteed to be already
4501 * - clean up and document the code.
4502 * - use String.Empty in class libs.
4505 /* Encode info required to decode shared GOT entries */
4506 buf_size = acfg->shared_patches->len * 64;
4507 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4508 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
4509 for (i = 0; i < acfg->shared_patches->len; ++i) {
4510 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
4512 /* No need to encode the patch type */
4513 got_info_offsets [i] = p - buf;
4514 encode_patch (acfg, ji, p, &p);
4517 g_assert (p - buf <= buf_size);
4519 acfg->stats.got_info_size = p - buf;
4521 /* Emit got_info table */
4522 sprintf (symbol, "got_info");
4523 emit_section_change (acfg, ".text", 1);
4524 emit_global (acfg, symbol, FALSE);
4525 emit_alignment (acfg, 8);
4526 emit_label (acfg, symbol);
4528 emit_bytes (acfg, buf, p - buf);
4530 /* Emit got_info_offsets table */
4531 sprintf (symbol, "got_info_offsets");
4532 emit_section_change (acfg, ".text", 1);
4533 emit_global (acfg, symbol, FALSE);
4534 emit_alignment (acfg, 8);
4535 emit_label (acfg, symbol);
4537 for (i = 0; i < acfg->shared_patches->len; ++i)
4538 emit_int32 (acfg, got_info_offsets [i]);
4540 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
4544 emit_got (MonoAotCompile *acfg)
4548 /* Don't make GOT global so accesses to it don't need relocations */
4549 sprintf (symbol, "got");
4550 emit_section_change (acfg, ".bss", 1);
4551 emit_alignment (acfg, 8);
4552 emit_label (acfg, symbol);
4553 if ((acfg->got_offset + acfg->num_trampoline_got_entries) > 0)
4554 emit_zero_bytes (acfg, (int)((acfg->got_offset + acfg->num_trampoline_got_entries) * sizeof (gpointer)));
4556 sprintf (symbol, "got_addr");
4557 emit_section_change (acfg, ".data", 1);
4558 emit_global (acfg, symbol, FALSE);
4559 emit_alignment (acfg, 8);
4560 emit_label (acfg, symbol);
4561 emit_pointer (acfg, "got");
4563 sprintf (symbol, "got_size");
4564 emit_section_change (acfg, ".data", 1);
4565 emit_global (acfg, symbol, FALSE);
4566 emit_alignment (acfg, 8);
4567 emit_label (acfg, symbol);
4568 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4572 emit_globals (MonoAotCompile *acfg)
4576 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4578 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4580 opts_str = g_strdup_printf ("%d", acfg->opts);
4581 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4584 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4586 if (acfg->aot_opts.bind_to_runtime_version)
4587 emit_string_symbol (acfg, "mono_runtime_version", FULL_VERSION);
4589 emit_string_symbol (acfg, "mono_runtime_version", "");
4592 * Some platforms like the iphone have no working dlsym (). To work around this,
4593 * we create an ELF ctor function which will be invoked by dlopen, and which
4594 * will call a function in the AOT loader to register the symbols used by the
4596 * When static linking, we emit a global which will point to the symbol table.
4598 if (acfg->aot_opts.no_dlsym) {
4602 if (acfg->aot_opts.static_link)
4603 /* Emit a string holding the assembly name */
4604 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4606 /* Emit the names */
4607 for (i = 0; i < acfg->globals->len; ++i) {
4608 char *name = g_ptr_array_index (acfg->globals, i);
4610 sprintf (symbol, "name_%d", i);
4611 emit_section_change (acfg, ".text", 1);
4612 emit_label (acfg, symbol);
4613 emit_string (acfg, name);
4616 /* Emit the globals table */
4617 sprintf (symbol, "globals");
4618 emit_section_change (acfg, ".data", 0);
4619 /* This is not a global, since it is accessed by the init function */
4620 emit_alignment (acfg, 8);
4621 emit_label (acfg, symbol);
4623 for (i = 0; i < acfg->globals->len; ++i) {
4624 char *name = g_ptr_array_index (acfg->globals, i);
4626 sprintf (symbol, "name_%d", i);
4627 emit_pointer (acfg, symbol);
4629 sprintf (symbol, "%s", name);
4630 emit_pointer (acfg, symbol);
4632 /* Null terminate the table */
4633 emit_pointer (acfg, NULL);
4634 emit_pointer (acfg, NULL);
4636 if (acfg->aot_opts.static_link) {
4640 * Emit a global symbol which can be passed by an embedding app to
4641 * mono_aot_register_module ().
4643 #if defined(__MACH__)
4644 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4646 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4649 /* Get rid of characters which cannot occur in symbols */
4651 for (p = symbol; *p; ++p) {
4652 if (!(isalnum (*p) || *p == '_'))
4655 acfg->static_linking_symbol = g_strdup (symbol);
4656 emit_global_inner (acfg, symbol, FALSE);
4657 emit_alignment (acfg, 8);
4658 emit_label (acfg, symbol);
4659 emit_pointer (acfg, "globals");
4661 sprintf (symbol, "init_%s", acfg->image->assembly->aname.name);
4662 emit_section_change (acfg, ".text", 1);
4663 emit_alignment (acfg, 8);
4664 emit_label (acfg, symbol);
4665 #ifdef USE_BIN_WRITER
4666 g_assert_not_reached ();
4669 fprintf (acfg->fp, "leaq globals(%%rip), %%rdi\n");
4670 fprintf (acfg->fp, "call mono_aot_register_globals@PLT\n");
4671 fprintf (acfg->fp, "ret\n");
4672 fprintf (acfg->fp, ".section .ctors,\"aw\",@progbits\n");
4673 emit_alignment (acfg, 8);
4674 emit_pointer (acfg, symbol);
4675 #elif defined(__arm__) && defined(__MACH__)
4677 fprintf (acfg->fp, ".text\n");
4678 fprintf (acfg->fp, ".align 3\n");
4680 fprintf (acfg->fp, "ldr r0, .L5\n");
4681 fprintf (acfg->fp, ".LPIC0:\n");
4682 fprintf (acfg->fp, "add r0, pc, r0\n");
4683 fprintf (acfg->fp, "ldr r0, [r0]\n");
4684 fprintf (acfg->fp, "b _mono_aot_register_globals@PLT\n");
4685 fprintf (acfg->fp, ".align 2\n");
4687 fprintf (acfg->fp, ".L5:\n");
4688 fprintf (acfg->fp, ".long globals_ptr-(.LPIC0+8)\n");
4690 fprintf (acfg->fp, ".data\n");
4691 fprintf (acfg->fp, ".align 2\n");
4692 fprintf (acfg->fp, "globals_ptr:\n");
4693 fprintf (acfg->fp, ".long globals\n");
4695 fprintf (acfg->fp, ".mod_init_func\n");
4696 fprintf (acfg->fp, ".align 2\n");
4697 fprintf (acfg->fp, ".long %s@target1\n", symbol);
4699 #elif defined(__arm__)
4701 * Taken from gcc generated code for:
4703 * void foo () { bar (&i); }
4704 * gcc --shared -fPIC -O2
4706 fprintf (acfg->fp, "ldr r3, .L5\n");
4707 fprintf (acfg->fp, "ldr r0, .L5+4\n");
4708 fprintf (acfg->fp, ".LPIC0:\n");
4709 fprintf (acfg->fp, "add r3, pc, r3\n");
4710 fprintf (acfg->fp, "add r0, r3, r0\n");
4711 fprintf (acfg->fp, "b mono_aot_register_globals(PLT)\n");
4713 fprintf (acfg->fp, ".L5:\n");
4714 fprintf (acfg->fp, ".word _GLOBAL_OFFSET_TABLE_-(.LPIC0+8)\n");
4715 fprintf (acfg->fp, ".word globals(GOTOFF)\n");
4717 fprintf (acfg->fp, ".section .init_array,\"aw\",%%init_array\n");
4718 fprintf (acfg->fp, ".align 2\n");
4719 fprintf (acfg->fp, ".word %s(target1)\n", symbol);
4721 g_assert_not_reached ();
4729 acfg_free (MonoAotCompile *acfg)
4733 for (i = 0; i < acfg->nmethods; ++i)
4735 g_free (acfg->cfgs [i]);
4736 g_free (acfg->cfgs);
4737 g_free (acfg->static_linking_symbol);
4738 g_ptr_array_free (acfg->methods, TRUE);
4739 g_ptr_array_free (acfg->shared_patches, TRUE);
4740 g_ptr_array_free (acfg->image_table, TRUE);
4741 g_ptr_array_free (acfg->globals, TRUE);
4742 g_hash_table_destroy (acfg->method_indexes);
4743 g_hash_table_destroy (acfg->plt_offset_to_patch);
4744 g_hash_table_destroy (acfg->patch_to_plt_offset);
4745 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
4746 g_hash_table_destroy (acfg->method_to_cfg);
4747 g_hash_table_destroy (acfg->token_info_hash);
4748 g_hash_table_destroy (acfg->image_hash);
4749 mono_mempool_destroy (acfg->mempool);
4754 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4756 MonoImage *image = ass->image;
4758 int i, res, methods_len;
4759 MonoAotCompile *acfg;
4763 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4765 acfg = g_new0 (MonoAotCompile, 1);
4766 acfg->methods = g_ptr_array_new ();
4767 acfg->method_indexes = g_hash_table_new (NULL, NULL);
4768 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4769 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4770 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4771 acfg->shared_patches = g_ptr_array_new ();
4772 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4773 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4774 acfg->image_hash = g_hash_table_new (NULL, NULL);
4775 acfg->image_table = g_ptr_array_new ();
4776 acfg->globals = g_ptr_array_new ();
4777 acfg->image = image;
4779 acfg->mempool = mono_mempool_new ();
4780 acfg->extra_methods = g_ptr_array_new ();
4781 InitializeCriticalSection (&acfg->mutex);
4783 mono_aot_parse_options (aot_options, &acfg->aot_opts);
4785 load_profile_files (acfg);
4789 acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 10240 : 0;
4791 acfg->method_index = 1;
4793 /* Collect methods */
4794 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4796 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4798 method = mono_get_method (acfg->image, token, NULL);
4800 /* Load all methods eagerly to skip the slower lazy loading code */
4801 mono_class_setup_methods (method->klass);
4803 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4804 /* Compile the wrapper instead */
4805 /* We do this here instead of add_wrappers () because it is easy to do it here */
4806 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4810 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4811 add_method_with_index (acfg, method, i);
4812 acfg->method_index ++;
4815 add_generic_instances (acfg);
4817 if (acfg->aot_opts.full_aot)
4818 add_wrappers (acfg);
4820 acfg->cfgs_size = acfg->methods->len + 32;
4821 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
4823 /* PLT offset 0 is reserved for the PLT trampoline */
4824 acfg->plt_offset = 1;
4826 /* Compile methods */
4829 if (acfg->aot_opts.nthreads > 0) {
4834 gpointer *user_data;
4835 MonoMethod **methods;
4837 methods_len = acfg->methods->len;
4839 len = acfg->methods->len / acfg->aot_opts.nthreads;
4842 * Partition the list of methods into fragments, and hand it to threads to
4845 threads = g_ptr_array_new ();
4846 /* Make a copy since acfg->methods is modified by compile_method () */
4847 methods = g_new0 (MonoMethod*, methods_len);
4848 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
4849 for (i = 0; i < methods_len; ++i)
4850 methods [i] = g_ptr_array_index (acfg->methods, i);
4852 while (i < methods_len) {
4853 frag = g_ptr_array_new ();
4854 for (j = 0; j < len; ++j) {
4855 if (i < methods_len) {
4856 g_ptr_array_add (frag, methods [i]);
4861 user_data = g_new0 (gpointer, 3);
4862 user_data [0] = mono_domain_get ();
4863 user_data [1] = acfg;
4864 user_data [2] = frag;
4866 handle = CreateThread (NULL, 0, (WapiThreadStart)compile_thread_main, user_data, 0, NULL);
4867 g_ptr_array_add (threads, handle);
4871 for (i = 0; i < threads->len; ++i) {
4872 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
4878 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
4879 for (i = methods_len; i < acfg->methods->len; ++i) {
4880 /* This can new methods to acfg->methods */
4881 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4886 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
4890 alloc_got_slots (acfg);
4896 emit_extra_methods (acfg);
4898 emit_method_order (acfg);
4900 emit_trampolines (acfg);
4902 emit_class_name_table (acfg);
4904 emit_got_info (acfg);
4906 emit_exception_info (acfg);
4908 emit_class_info (acfg);
4912 emit_image_table (acfg);
4916 emit_globals (acfg);
4918 sprintf (symbol, "mem_end");
4919 emit_section_change (acfg, ".text", 1);
4920 emit_global (acfg, symbol, FALSE);
4921 emit_alignment (acfg, 8);
4922 emit_label (acfg, symbol);
4926 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
4928 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)));
4931 res = emit_writeout (acfg);
4937 acfg->stats.link_time = TV_ELAPSED (atv, btv);
4939 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);
4940 if (acfg->stats.genericcount)
4941 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4942 if (acfg->stats.abscount)
4943 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4944 if (acfg->stats.wrappercount)
4945 printf ("%d methods contain wrapper references (%d%%)\n", acfg->stats.wrappercount, acfg->stats.mcount ? (acfg->stats.wrappercount * 100) / acfg->stats.mcount : 100);
4946 if (acfg->stats.lmfcount)
4947 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4948 if (acfg->stats.ocount)
4949 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4950 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);
4951 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4952 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);
4954 printf ("GOT slot distribution:\n");
4955 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4956 if (acfg->stats.got_slot_types [i])
4957 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4969 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)