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>
35 #ifndef PLATFORM_WIN32
45 #include <limits.h> /* for PAGESIZE */
50 #include <mono/metadata/tabledefs.h>
51 #include <mono/metadata/class.h>
52 #include <mono/metadata/object.h>
53 #include <mono/metadata/tokentype.h>
54 #include <mono/metadata/appdomain.h>
55 #include <mono/metadata/debug-helpers.h>
56 #include <mono/metadata/assembly.h>
57 #include <mono/metadata/metadata-internals.h>
58 #include <mono/metadata/marshal.h>
59 #include <mono/metadata/gc-internal.h>
60 #include <mono/metadata/method-builder.h>
61 #include <mono/metadata/monitor.h>
62 #include <mono/utils/mono-logger.h>
63 #include <mono/utils/mono-compiler.h>
64 #include <mono/utils/mono-time.h>
66 #ifndef PLATFORM_WIN32
67 #include <mono/utils/freebsd-elf32.h>
68 #include <mono/utils/freebsd-elf64.h>
76 #define TV_DECLARE(name) gint64 name
77 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
78 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
81 #define SHARED_EXT ".dll"
82 #elif defined(__ppc__) && defined(__MACH__)
83 #define SHARED_EXT ".dylib"
85 #define SHARED_EXT ".so"
88 #if defined(sparc) || defined(__ppc__) || defined(__powerpc__) || defined(__MACH__)
89 #define AS_STRING_DIRECTIVE ".asciz"
92 #define AS_STRING_DIRECTIVE ".string"
97 // .byte generates 1 byte per expression.
98 // .short generates 2 bytes per expression.
99 // .long generates 4 bytes per expression.
100 // .quad generates 8 bytes per expression.
102 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
103 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
105 typedef struct MonoAotOptions {
108 gboolean write_symbols;
109 gboolean metadata_only;
110 gboolean bind_to_runtime_version;
113 gboolean static_link;
118 typedef struct MonoAotStats {
119 int ccount, mcount, lmfcount, abscount, wrappercount, gcount, ocount, genericcount;
120 int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
121 int methods_without_got_slots, direct_calls, all_calls;
123 int got_slot_types [MONO_PATCH_INFO_NONE];
124 int jit_time, gen_time, link_time;
127 #if defined(__x86_64__) && defined(HAVE_ELF_H)
128 //#define USE_ELF_WRITER 1
129 #define USE_ELF_RELA 1
132 //#define USE_ELF_WRITER 1
134 #if defined(USE_ELF_WRITER)
135 #define USE_BIN_WRITER 1
138 #ifdef USE_BIN_WRITER
140 typedef struct _BinSymbol BinSymbol;
141 typedef struct _BinReloc BinReloc;
142 typedef struct _BinSection BinSection;
156 typedef struct MonoAotCompile {
159 GHashTable *method_indexes;
162 GHashTable *patch_to_plt_offset;
163 GHashTable *plt_offset_to_patch;
164 GHashTable *patch_to_shared_got_offset;
165 GPtrArray *shared_patches;
166 GHashTable *image_hash;
167 GHashTable *method_to_cfg;
168 GHashTable *token_info_hash;
169 GPtrArray *extra_methods;
170 GPtrArray *image_table;
173 /* Number of trampolines emitted into the AOT file */
174 guint32 num_aot_trampolines;
175 guint32 got_offset, plt_offset;
176 /* Number of GOT entries reserved for trampolines */
177 guint32 num_trampoline_got_entries;
178 MonoAotOptions aot_opts;
181 MonoMemPool *mempool;
184 char *static_linking_symbol;
185 CRITICAL_SECTION mutex;
186 #ifdef USE_BIN_WRITER
188 BinSection *sections;
189 BinSection *cur_section;
190 BinReloc *relocations;
196 int mode; /* emit mode */
197 int col_count; /* bytes emitted per .byte line */
201 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
202 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
204 #ifdef HAVE_ARRAY_ELEM_INIT
205 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
206 #define MSGSTRFIELD1(line) str##line
207 static const struct msgstr_t {
208 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
209 #include "patch-info.h"
212 #define PATCH_INFO(a,b) b,
213 #include "patch-info.h"
216 static const gint16 opidx [] = {
217 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
218 #include "patch-info.h"
223 get_patch_name (int info)
225 return (const char*)&opstr + opidx [info];
229 #define PATCH_INFO(a,b) b,
230 static const char* const
231 patch_types [MONO_PATCH_INFO_NUM + 1] = {
232 #include "patch-info.h"
237 get_patch_name (int info)
239 return patch_types [info];
245 emit_global (MonoAotCompile *acfg, const char *name, gboolean func);
248 is_got_patch (MonoJumpInfoType patch_type)
253 static G_GNUC_UNUSED int
254 ilog2(register int value)
257 while (value & ~0xf) count += 4, value >>= 4;
258 while (value) count++, value >>= 1;
262 #ifdef USE_BIN_WRITER
264 typedef struct _BinLabel BinLabel;
275 BinSection *val2_section;
287 gboolean is_function;
305 emit_start (MonoAotCompile *acfg)
307 acfg->labels = g_hash_table_new (g_str_hash, g_str_equal);
311 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
315 if (acfg->cur_section && acfg->cur_section->subsection == subsection_index
316 && strcmp (acfg->cur_section->name, section_name) == 0)
318 for (section = acfg->sections; section; section = section->next) {
319 if (section->subsection == subsection_index && strcmp (section->name, section_name) == 0) {
320 acfg->cur_section = section;
325 section = g_new0 (BinSection, 1);
326 section->name = g_strdup (section_name);
327 section->subsection = subsection_index;
328 section->next = acfg->sections;
329 acfg->sections = section;
330 acfg->cur_section = section;
335 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
337 BinSymbol *symbol = g_new0 (BinSymbol, 1);
338 symbol->name = g_strdup (name);
339 symbol->is_function = func;
340 symbol->is_global = TRUE;
341 symbol->section = acfg->cur_section;
342 /* FIXME: we align after this call... */
343 symbol->offset = symbol->section->cur_offset;
344 symbol->next = acfg->symbols;
345 acfg->symbols = symbol;
349 emit_label (MonoAotCompile *acfg, const char *name)
351 BinLabel *label = g_new0 (BinLabel, 1);
352 label->name = g_strdup (name);
353 label->section = acfg->cur_section;
354 label->offset = acfg->cur_section->cur_offset;
355 g_hash_table_insert (acfg->labels, label->name, label);
359 emit_ensure_buffer (BinSection *section, int size)
361 int new_offset = section->cur_offset + size;
362 if (new_offset >= section->data_len) {
363 int new_size = section->data_len? section->data_len * 2: 256;
365 while (new_size <= new_offset)
367 data = g_malloc0 (new_size);
368 memcpy (data, section->data, section->data_len);
369 g_free (section->data);
370 section->data = data;
371 section->data_len = new_size;
376 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
378 emit_ensure_buffer (acfg->cur_section, size);
379 memcpy (acfg->cur_section->data + acfg->cur_section->cur_offset, buf, size);
380 acfg->cur_section->cur_offset += size;
384 emit_string (MonoAotCompile *acfg, const char *value)
386 int size = strlen (value) + 1;
387 emit_bytes (acfg, (const guint8*)value, size);
391 emit_line (MonoAotCompile *acfg)
393 /* Nothing to do in binary writer */
397 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
399 emit_section_change (acfg, ".text", 1);
400 emit_global (acfg, name, FALSE);
401 emit_label (acfg, name);
402 emit_string (acfg, value);
406 emit_alignment (MonoAotCompile *acfg, int size)
408 int offset = acfg->cur_section->cur_offset;
410 offset += (size - 1);
411 offset &= ~(size - 1);
412 add = offset - acfg->cur_section->cur_offset;
414 emit_ensure_buffer (acfg->cur_section, add);
415 acfg->cur_section->cur_offset += add;
420 emit_pointer (MonoAotCompile *acfg, const char *target)
426 g_assert_not_reached ();
427 emit_alignment (acfg, sizeof (gpointer));
428 reloc = g_new0 (BinReloc, 1);
429 reloc->val1 = g_strdup (target);
430 reloc->section = acfg->cur_section;
431 reloc->section_offset = acfg->cur_section->cur_offset;
432 reloc->next = acfg->relocations;
433 acfg->relocations = reloc;
434 if (strcmp (reloc->section->name, ".data") == 0) {
436 g_print ("reloc: %s at %d\n", target, acfg->cur_section->cur_offset);
438 acfg->cur_section->cur_offset += sizeof (gpointer);
442 emit_int16 (MonoAotCompile *acfg, int value)
445 emit_ensure_buffer (acfg->cur_section, 2);
446 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
447 acfg->cur_section->cur_offset += 2;
448 /* FIXME: little endian */
450 data [1] = value >> 8;
454 emit_int32 (MonoAotCompile *acfg, int value)
457 emit_ensure_buffer (acfg->cur_section, 4);
458 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
459 acfg->cur_section->cur_offset += 4;
460 /* FIXME: little endian */
462 data [1] = value >> 8;
463 data [2] = value >> 16;
464 data [3] = value >> 24;
468 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
471 reloc = mono_mempool_alloc0 (acfg->mempool, sizeof (BinReloc));
472 reloc->val1 = mono_mempool_strdup (acfg->mempool, end);
473 if (strcmp (start, ".") == 0) {
474 reloc->val2_section = acfg->cur_section;
475 reloc->val2_offset = acfg->cur_section->cur_offset;
477 reloc->val2 = mono_mempool_strdup (acfg->mempool, start);
479 reloc->offset = offset;
480 reloc->section = acfg->cur_section;
481 reloc->section_offset = acfg->cur_section->cur_offset;
482 reloc->next = acfg->relocations;
483 acfg->relocations = reloc;
484 acfg->cur_section->cur_offset += 4;
485 /*if (strcmp (reloc->section->name, ".data") == 0) {
487 g_print ("reloc: %s - %s + %d at %d\n", end, start, offset, acfg->cur_section->cur_offset - 4);
492 emit_zero_bytes (MonoAotCompile *acfg, int num)
494 emit_ensure_buffer (acfg->cur_section, num);
495 acfg->cur_section->cur_offset += num;
498 #ifdef USE_ELF_WRITER
518 #if SIZEOF_VOID_P == 4
520 typedef Elf32_Ehdr ElfHeader;
521 typedef Elf32_Shdr ElfSectHeader;
522 typedef Elf32_Phdr ElfProgHeader;
523 typedef Elf32_Sym ElfSymbol;
524 typedef Elf32_Rel ElfReloc;
525 typedef Elf32_Rela ElfRelocA;
526 typedef Elf32_Dyn ElfDynamic;
530 typedef Elf64_Ehdr ElfHeader;
531 typedef Elf64_Shdr ElfSectHeader;
532 typedef Elf64_Phdr ElfProgHeader;
533 typedef Elf64_Sym ElfSymbol;
534 typedef Elf64_Rel ElfReloc;
535 typedef Elf64_Rela ElfRelocA;
536 typedef Elf64_Dyn ElfDynamic;
548 static SectInfo section_info [] = {
550 {".hash", SHT_HASH, 4, 2, SIZEOF_VOID_P},
551 {".dynsym", SHT_DYNSYM, sizeof (ElfSymbol), 2, SIZEOF_VOID_P},
552 {".dynstr", SHT_STRTAB, 0, 2, 1},
553 {".rel.dyn", SHT_REL, sizeof (ElfReloc), 2, SIZEOF_VOID_P},
554 {".rela.dyn", SHT_RELA, sizeof (ElfRelocA), 2, SIZEOF_VOID_P},
555 {".text", SHT_PROGBITS, 0, 6, 4096},
556 {".dynamic", SHT_DYNAMIC, sizeof (ElfDynamic), 3, SIZEOF_VOID_P},
557 {".got.plt", SHT_PROGBITS, SIZEOF_VOID_P, 3, SIZEOF_VOID_P},
558 {".data", SHT_PROGBITS, 0, 3, 8},
559 {".bss", SHT_NOBITS, 0, 3, 8},
560 {".shstrtab", SHT_STRTAB, 0, 0, 1},
561 {".symtab", SHT_SYMTAB, sizeof (ElfSymbol), 0, SIZEOF_VOID_P},
562 {".strtab", SHT_STRTAB, 0, 0, 1}
571 str_table_add (ElfStrTable *table, const char* value)
575 table->data = g_string_new_len ("", 1);
576 table->hash = g_hash_table_new (g_str_hash, g_str_equal);
578 idx = GPOINTER_TO_UINT (g_hash_table_lookup (table->hash, value));
581 idx = table->data->len;
582 g_string_append (table->data, value);
583 g_string_append_c (table->data, 0);
584 g_hash_table_insert (table->hash, (void*)value, GUINT_TO_POINTER (idx));
589 append_subsection (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection *sect, BinSection *add)
591 int offset = sect->cur_offset;
592 /*offset += (sheaders [sect->shidx].sh_addralign - 1);
593 offset &= ~(sheaders [sect->shidx].sh_addralign - 1);*/
596 emit_ensure_buffer (sect, offset);
597 g_print ("section %s aligned to %d from %d\n", sect->name, offset, sect->cur_offset);
598 sect->cur_offset = offset;
600 emit_ensure_buffer (sect, add->cur_offset);
601 memcpy (sect->data + sect->cur_offset, add->data, add->cur_offset);
603 sect->cur_offset += add->cur_offset;
604 add->cur_offset = offset; /* it becomes the offset in the parent section */
605 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);
610 /* merge the subsections */
612 collect_sections (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection **out, int num)
614 int i, j, maxs, num_sections;
619 for (sect = acfg->sections; sect; sect = sect->next) {
620 if (sect->subsection == 0) {
621 out [num_sections++] = sect;
622 g_assert (num_sections < num);
623 if (strcmp (sect->name, ".text") == 0) {
624 sect->shidx = SECT_TEXT;
625 } else if (strcmp (sect->name, ".data") == 0) {
626 sect->shidx = SECT_DATA;
627 } else if (strcmp (sect->name, ".bss") == 0) {
628 sect->shidx = SECT_BSS;
631 maxs = MAX (maxs, sect->subsection);
633 for (i = 0; i < num_sections; i++) {
634 for (j = 1; j <= maxs; ++j) {
635 for (sect = acfg->sections; sect; sect = sect->next) {
636 if (sect->subsection == j && strcmp (out [i]->name, sect->name) == 0) {
637 append_subsection (acfg, sheaders, out [i], sect);
646 elf_hash (const unsigned char *name)
648 unsigned long h = 0, g;
650 h = (h << 4) + *name++;
651 if ((g = h & 0xf0000000))
658 #define NUM_BUCKETS 17
661 build_hash (MonoAotCompile *acfg, int num_sections, ElfStrTable *dynstr)
664 int num_symbols = 1 + num_sections + 3;
667 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
668 if (!symbol->is_global)
671 str_table_add (dynstr, symbol->name);
672 /*g_print ("adding sym: %s\n", symbol->name);*/
674 str_table_add (dynstr, "__bss_start");
675 str_table_add (dynstr, "_edata");
676 str_table_add (dynstr, "_end");
678 data = g_new0 (int, num_symbols + 2 + NUM_BUCKETS);
679 data [0] = NUM_BUCKETS;
680 data [1] = num_symbols;
686 get_label_addr (MonoAotCompile *acfg, const char *name)
693 lab = g_hash_table_lookup (acfg->labels, name);
694 section = lab->section;
695 offset = lab->offset;
696 if (section->parent) {
697 value = section->parent->virt_offset + section->cur_offset + offset;
699 value = section->virt_offset + offset;
705 collect_syms (MonoAotCompile *acfg, int *hash, ElfStrTable *strtab, ElfSectHeader *sheaders, int *num_syms)
716 symbols = g_new0 (ElfSymbol, hash [1]);
718 symbols = g_new0 (ElfSymbol, *num_syms + SECT_NUM + 10); /* FIXME */
720 /* the first symbol is undef, all zeroes */
724 for (j = 1; j < SECT_NUM; ++j) {
725 symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
726 symbols [i].st_shndx = j;
727 symbols [i].st_value = sheaders [j].sh_addr;
731 for (section = acfg->sections; section; section = section->next) {
734 symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
735 if (strcmp (section->name, ".text") == 0) {
736 symbols [i].st_shndx = SECT_TEXT;
737 section->shidx = SECT_TEXT;
738 section->file_offset = 4096;
739 symbols [i].st_value = section->virt_offset;
740 } else if (strcmp (section->name, ".data") == 0) {
741 symbols [i].st_shndx = SECT_DATA;
742 section->shidx = SECT_DATA;
743 section->file_offset = 4096 + 28; /* FIXME */
744 symbols [i].st_value = section->virt_offset;
745 } else if (strcmp (section->name, ".bss") == 0) {
746 symbols [i].st_shndx = SECT_BSS;
747 section->shidx = SECT_BSS;
748 section->file_offset = 4096 + 28 + 8; /* FIXME */
749 symbols [i].st_value = section->virt_offset;
754 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
757 if (!symbol->is_global)
759 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, symbol->is_function? STT_FUNC : STT_OBJECT);
760 symbols [i].st_name = str_table_add (strtab, symbol->name);
761 /*g_print ("sym name %s tabled to %d\n", symbol->name, symbols [i].st_name);*/
762 section = symbol->section;
763 symbols [i].st_shndx = section->parent? section->parent->shidx: section->shidx;
764 lab = g_hash_table_lookup (acfg->labels, symbol->name);
765 offset = lab->offset;
766 if (section->parent) {
767 symbols [i].st_value = section->parent->virt_offset + section->cur_offset + offset;
769 symbols [i].st_value = section->virt_offset + offset;
773 /* add special symbols */
774 symbols [i].st_name = str_table_add (strtab, "__bss_start");
775 symbols [i].st_shndx = 0xfff1;
776 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
778 symbols [i].st_name = str_table_add (strtab, "_edata");
779 symbols [i].st_shndx = 0xfff1;
780 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
782 symbols [i].st_name = str_table_add (strtab, "_end");
783 symbols [i].st_shndx = 0xfff1;
784 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
790 /* add to hash table */
793 chain = hash + 2 + hash [0];
794 for (i = 0; i < hash [1]; ++i) {
796 /*g_print ("checking %d '%s' (sym %d)\n", symbols [i].st_name, strtab->data->str + symbols [i].st_name, i);*/
797 if (!symbols [i].st_name)
799 hashc = elf_hash ((guint8*)strtab->data->str + symbols [i].st_name);
800 slot = hashc % hash [0];
801 /*g_print ("hashing '%s' at slot %d (sym %d)\n", strtab->data->str + symbols [i].st_name, slot, i);*/
803 chain [i] = bucket [slot];
814 reloc_symbols (MonoAotCompile *acfg, ElfSymbol *symbols, ElfSectHeader *sheaders, ElfStrTable *strtab, gboolean dynamic)
822 for (section = acfg->sections; section; section = section->next) {
825 symbols [i].st_value = sheaders [section->shidx].sh_addr;
829 for (i = 1; i < SECT_NUM; ++i) {
830 symbols [i].st_value = sheaders [i].sh_addr;
833 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
836 if (dynamic && !symbol->is_global)
838 section = symbol->section;
839 lab = g_hash_table_lookup (acfg->labels, symbol->name);
840 offset = lab->offset;
841 if (section->parent) {
842 symbols [i].st_value = sheaders [section->parent->shidx].sh_addr + section->cur_offset + offset;
844 symbols [i].st_value = sheaders [section->shidx].sh_addr + offset;
849 symbols [i].st_value = sheaders [SECT_BSS].sh_addr;
852 symbols [i].st_value = sheaders [SECT_DATA].sh_addr + sheaders [SECT_DATA].sh_size;
855 symbols [i].st_value = sheaders [SECT_BSS].sh_addr + sheaders [SECT_BSS].sh_size;
860 resolve_reloc (MonoAotCompile *acfg, BinReloc *reloc, guint8 **out_data, gsize *out_vaddr, gsize *out_start_val, gsize *out_end_val)
863 gsize end_val, start_val;
866 end_val = get_label_addr (acfg, reloc->val1);
868 start_val = get_label_addr (acfg, reloc->val2);
869 } else if (reloc->val2_section) {
870 start_val = reloc->val2_offset;
871 if (reloc->val2_section->parent)
872 start_val += reloc->val2_section->parent->virt_offset + reloc->val2_section->cur_offset;
874 start_val += reloc->val2_section->virt_offset;
878 end_val = end_val - start_val + reloc->offset;
879 if (reloc->section->parent) {
880 data = reloc->section->parent->data;
881 data += reloc->section->cur_offset;
882 data += reloc->section_offset;
883 vaddr = reloc->section->parent->virt_offset;
884 vaddr += reloc->section->cur_offset;
885 vaddr += reloc->section_offset;
887 data = reloc->section->data;
888 data += reloc->section_offset;
889 vaddr = reloc->section->virt_offset;
890 vaddr += reloc->section_offset;
893 *out_start_val = start_val;
894 *out_end_val = end_val;
902 resolve_relocations (MonoAotCompile *acfg)
906 gsize end_val, start_val;
911 rr = g_new0 (ElfRelocA, acfg->num_relocs);
914 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
915 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
916 /* FIXME: little endian */
918 data [1] = end_val >> 8;
919 data [2] = end_val >> 16;
920 data [3] = end_val >> 24;
921 if (start_val == 0) {
922 rr [i].r_offset = vaddr;
923 rr [i].r_info = R_X86_64_RELATIVE;
924 rr [i].r_addend = end_val;
926 g_assert (i <= acfg->num_relocs);
932 #else /* USE_ELF_RELA */
935 resolve_relocations (MonoAotCompile *acfg)
939 gsize end_val, start_val;
944 rr = g_new0 (ElfReloc, acfg->num_relocs);
947 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
948 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
949 /* FIXME: little endian */
951 data [1] = end_val >> 8;
952 data [2] = end_val >> 16;
953 data [3] = end_val >> 24;
954 if (start_val == 0) {
955 rr [i].r_offset = vaddr;
956 rr [i].r_info = R_386_RELATIVE;
958 g_assert (i <= acfg->num_relocs);
964 #endif /* USE_ELF_RELA */
967 emit_writeout (MonoAotCompile *acfg)
969 char *outfile_name, *tmp_outfile_name;
972 ElfProgHeader progh [3];
973 ElfSectHeader secth [SECT_NUM];
979 ElfStrTable str_table = {NULL, NULL};
980 ElfStrTable sh_str_table = {NULL, NULL};
981 ElfStrTable dyn_str_table = {NULL, NULL};
982 BinSection* sections [6];
983 BinSection *text_section = NULL, *data_section = NULL, *bss_section = NULL;
986 ElfDynamic dynamic [14];
988 int i, num_sections, file_offset, virt_offset, size, num_symtab;
991 g_assert (!acfg->aot_opts.asm_only);
993 if (acfg->aot_opts.outfile)
994 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
996 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
998 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1000 unlink (tmp_outfile_name);
1001 file = fopen (tmp_outfile_name, "w");
1004 /* Section headers */
1005 memset (§h, 0, sizeof (secth));
1006 memset (&dynamic, 0, sizeof (dynamic));
1007 memset (&header, 0, sizeof (header));
1009 for (i = 1; i < SECT_NUM; ++i) {
1010 secth [i].sh_name = str_table_add (&sh_str_table, section_info [i].name);
1011 secth [i].sh_type = section_info [i].type;
1012 secth [i].sh_addralign = section_info [i].align;
1013 secth [i].sh_flags = section_info [i].flags;
1014 secth [i].sh_entsize = section_info [i].esize;
1016 secth [SECT_DYNSYM].sh_info = SIZEOF_VOID_P == 4 ? 4 : 2;
1017 secth [SECT_SYMTAB].sh_info = SIZEOF_VOID_P == 4 ? 20 : 17;
1018 secth [SECT_HASH].sh_link = SECT_DYNSYM;
1019 secth [SECT_DYNSYM].sh_link = SECT_DYNSTR;
1020 secth [SECT_REL_DYN].sh_link = SECT_DYNSYM;
1021 secth [SECT_RELA_DYN].sh_link = SECT_DYNSYM;
1022 secth [SECT_DYNAMIC].sh_link = SECT_DYNSTR;
1023 secth [SECT_SYMTAB].sh_link = SECT_STRTAB;
1025 num_sections = collect_sections (acfg, secth, sections, 6);
1026 hash = build_hash (acfg, num_sections, &dyn_str_table);
1027 num_symtab = hash [1]; /* FIXME */
1028 g_print ("num_sections: %d\n", num_sections);
1029 g_print ("dynsym: %d, dynstr size: %d\n", hash [1], (int)dyn_str_table.data->len);
1030 for (i = 0; i < num_sections; ++i) {
1031 g_print ("section %s, size: %d, %x\n", sections [i]->name, sections [i]->cur_offset, sections [i]->cur_offset);
1034 /* at this point we know where in the file the first segment sections go */
1035 dynsym = collect_syms (acfg, hash, &dyn_str_table, NULL, NULL);
1036 num_local_syms = hash [1];
1037 symtab = collect_syms (acfg, NULL, &str_table, secth, &num_local_syms);
1039 for (i = 0; i < num_sections; ++i) {
1040 if (sections [i]->shidx == SECT_TEXT) {
1041 text_section = sections [i];
1042 } else if (sections [i]->shidx == SECT_DATA) {
1043 data_section = sections [i];
1044 } else if (sections [i]->shidx == SECT_BSS) {
1045 bss_section = sections [i];
1049 file_offset = virt_offset = sizeof (header) + sizeof (progh);
1050 secth [SECT_HASH].sh_addr = secth [SECT_HASH].sh_offset = file_offset;
1051 size = sizeof (int) * (2 + hash [0] + hash [1]);
1052 virt_offset = (file_offset += size);
1053 secth [SECT_HASH].sh_size = size;
1054 secth [SECT_DYNSYM].sh_addr = secth [SECT_DYNSYM].sh_offset = file_offset;
1055 size = sizeof (ElfSymbol) * hash [1];
1056 virt_offset = (file_offset += size);
1057 secth [SECT_DYNSYM].sh_size = size;
1058 secth [SECT_DYNSTR].sh_addr = secth [SECT_DYNSTR].sh_offset = file_offset;
1059 size = dyn_str_table.data->len;
1060 virt_offset = (file_offset += size);
1061 secth [SECT_DYNSTR].sh_size = size;
1063 file_offset &= ~(4-1);
1064 secth [SECT_REL_DYN].sh_addr = secth [SECT_REL_DYN].sh_offset = file_offset;
1065 #ifndef USE_ELF_RELA
1066 size = sizeof (ElfReloc) * acfg->num_relocs;
1070 virt_offset = (file_offset += size);
1071 secth [SECT_REL_DYN].sh_size = size;
1072 secth [SECT_RELA_DYN].sh_addr = secth [SECT_RELA_DYN].sh_offset = file_offset;
1074 size = sizeof (ElfRelocA) * acfg->num_relocs;
1078 virt_offset = (file_offset += size);
1079 secth [SECT_RELA_DYN].sh_size = size;
1080 file_offset += 4096-1;
1081 file_offset &= ~(4096-1);
1082 virt_offset = file_offset;
1083 secth [SECT_TEXT].sh_addr = secth [SECT_TEXT].sh_offset = file_offset;
1084 size = text_section->cur_offset;
1085 secth [SECT_TEXT].sh_size = size;
1086 file_offset += size;
1088 file_offset &= ~(4-1);
1089 virt_offset = file_offset;
1090 /* .dynamic, .got.plt, .data, .bss here */
1091 /* Have to increase the virt offset since these go to a separate segment */
1092 virt_offset += PAGESIZE;
1093 secth [SECT_DYNAMIC].sh_addr = virt_offset;
1094 secth [SECT_DYNAMIC].sh_offset = file_offset;
1095 size = sizeof (dynamic);
1096 secth [SECT_DYNAMIC].sh_size = size;
1099 file_offset += size;
1100 virt_offset += size;
1101 secth [SECT_GOT_PLT].sh_addr = virt_offset;
1102 secth [SECT_GOT_PLT].sh_offset = file_offset;
1104 secth [SECT_GOT_PLT].sh_size = size;
1107 file_offset += size;
1108 virt_offset += size;
1109 secth [SECT_DATA].sh_addr = virt_offset;
1110 secth [SECT_DATA].sh_offset = file_offset;
1111 size = data_section->cur_offset;
1112 secth [SECT_DATA].sh_size = size;
1115 file_offset += size;
1116 virt_offset += size;
1117 secth [SECT_BSS].sh_addr = virt_offset;
1118 secth [SECT_BSS].sh_offset = file_offset;
1119 size = bss_section->cur_offset;
1120 secth [SECT_BSS].sh_size = size;
1122 /* virtual doesn't matter anymore */
1123 secth [SECT_SHSTRTAB].sh_offset = file_offset;
1124 size = sh_str_table.data->len;
1125 secth [SECT_SHSTRTAB].sh_size = size;
1126 size += SIZEOF_VOID_P-1;
1127 size &= ~(SIZEOF_VOID_P-1);
1128 file_offset += size;
1129 secth [SECT_SYMTAB].sh_offset = file_offset;
1130 size = sizeof (ElfSymbol) * num_local_syms;
1131 secth [SECT_SYMTAB].sh_size = size;
1132 file_offset += size;
1133 secth [SECT_STRTAB].sh_offset = file_offset;
1134 size = str_table.data->len;
1135 secth [SECT_STRTAB].sh_size = size;
1136 file_offset += size;
1138 file_offset &= ~(4-1);
1140 text_section->file_offset = secth [SECT_TEXT].sh_offset;
1141 text_section->virt_offset = secth [SECT_TEXT].sh_addr;
1142 data_section->file_offset = secth [SECT_DATA].sh_offset;
1143 data_section->virt_offset = secth [SECT_DATA].sh_addr;
1144 bss_section->file_offset = secth [SECT_BSS].sh_offset;
1145 bss_section->virt_offset = secth [SECT_BSS].sh_addr;
1147 header.e_ident [EI_MAG0] = ELFMAG0;
1148 header.e_ident [EI_MAG1] = ELFMAG1;
1149 header.e_ident [EI_MAG2] = ELFMAG2;
1150 header.e_ident [EI_MAG3] = ELFMAG3;
1151 header.e_ident [EI_CLASS] = SIZEOF_VOID_P == 4 ? ELFCLASS32 : ELFCLASS64;
1152 header.e_ident [EI_DATA] = ELFDATA2LSB;
1153 header.e_ident [EI_VERSION] = EV_CURRENT;
1154 header.e_ident [EI_OSABI] = ELFOSABI_NONE;
1155 header.e_ident [EI_ABIVERSION] = 0;
1156 for (i = EI_PAD; i < EI_NIDENT; ++i)
1157 header.e_ident [i] = 0;
1159 header.e_type = ET_DYN;
1160 #if defined(__i386__)
1161 header.e_machine = EM_386;
1162 #elif defined(__x86_64__)
1163 header.e_machine = EM_X86_64;
1165 g_assert_not_reached ();
1167 header.e_version = 1;
1169 header.e_phoff = sizeof (header);
1170 header.e_ehsize = sizeof (header);
1171 header.e_phentsize = sizeof (ElfProgHeader);
1173 header.e_entry = secth [SECT_TEXT].sh_addr;
1174 header.e_shstrndx = SECT_SHSTRTAB;
1175 header.e_shentsize = sizeof (ElfSectHeader);
1176 header.e_shnum = SECT_NUM;
1177 header.e_shoff = file_offset;
1181 dynamic [i].d_tag = DT_HASH;
1182 dynamic [i].d_un.d_val = secth [SECT_HASH].sh_offset;
1184 dynamic [i].d_tag = DT_STRTAB;
1185 dynamic [i].d_un.d_val = secth [SECT_DYNSTR].sh_offset;
1187 dynamic [i].d_tag = DT_SYMTAB;
1188 dynamic [i].d_un.d_val = secth [SECT_DYNSYM].sh_offset;
1190 dynamic [i].d_tag = DT_STRSZ;
1191 dynamic [i].d_un.d_val = dyn_str_table.data->len;
1193 dynamic [i].d_tag = DT_SYMENT;
1194 dynamic [i].d_un.d_val = sizeof (ElfSymbol);
1197 dynamic [i].d_tag = DT_RELA;
1198 dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_offset;
1200 dynamic [i].d_tag = DT_RELASZ;
1201 dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_size;
1203 dynamic [i].d_tag = DT_RELAENT;
1204 dynamic [i].d_un.d_val = sizeof (ElfRelocA);
1207 dynamic [i].d_tag = DT_REL;
1208 dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_offset;
1210 dynamic [i].d_tag = DT_RELSZ;
1211 dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_size;
1213 dynamic [i].d_tag = DT_RELENT;
1214 dynamic [i].d_un.d_val = sizeof (ElfReloc);
1217 dynamic [i].d_tag = DT_RELCOUNT;
1218 dynamic [i].d_un.d_val = acfg->num_relocs;
1221 /* Program header */
1222 memset (&progh, 0, sizeof (progh));
1223 progh [0].p_type = PT_LOAD;
1224 progh [0].p_filesz = progh [0].p_memsz = secth [SECT_DYNAMIC].sh_offset;
1225 progh [0].p_align = 4096;
1226 progh [0].p_flags = 5;
1228 progh [1].p_type = PT_LOAD;
1229 progh [1].p_offset = secth [SECT_DYNAMIC].sh_offset;
1230 progh [1].p_vaddr = progh [1].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1231 progh [1].p_filesz = secth [SECT_BSS].sh_offset - secth [SECT_DYNAMIC].sh_offset;
1232 progh [1].p_memsz = secth [SECT_BSS].sh_addr + secth [SECT_BSS].sh_size - secth [SECT_DYNAMIC].sh_addr;
1233 progh [1].p_align = 4096;
1234 progh [1].p_flags = 6;
1236 progh [2].p_type = PT_DYNAMIC;
1237 progh [2].p_offset = secth [SECT_DYNAMIC].sh_offset;
1238 progh [2].p_vaddr = progh [2].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1239 progh [2].p_filesz = progh [2].p_memsz = secth [SECT_DYNAMIC].sh_size;
1240 progh [2].p_align = SIZEOF_VOID_P;
1241 progh [2].p_flags = 6;
1243 reloc_symbols (acfg, dynsym, secth, &dyn_str_table, TRUE);
1244 reloc_symbols (acfg, symtab, secth, &str_table, FALSE);
1245 relocs = resolve_relocations (acfg);
1247 fwrite (&header, sizeof (header), 1, file);
1248 fwrite (&progh, sizeof (progh), 1, file);
1249 fwrite (hash, sizeof (int) * (hash [0] + hash [1] + 2), 1, file);
1250 fwrite (dynsym, sizeof (ElfSymbol) * hash [1], 1, file);
1251 fwrite (dyn_str_table.data->str, dyn_str_table.data->len, 1, file);
1253 fseek (file, secth [SECT_REL_DYN].sh_offset, SEEK_SET);
1254 fwrite (relocs, sizeof (ElfReloc), acfg->num_relocs, file);
1257 fseek (file, secth [SECT_RELA_DYN].sh_offset, SEEK_SET);
1258 fwrite (relocs, secth [SECT_RELA_DYN].sh_size, 1, file);
1260 fseek (file, secth [SECT_TEXT].sh_offset, SEEK_SET);
1261 /* write .text, .data, .bss sections */
1262 fwrite (text_section->data, text_section->cur_offset, 1, file);
1265 fwrite (dynamic, sizeof (dynamic), 1, file);
1267 size = secth [SECT_DYNAMIC].sh_addr;
1268 fwrite (&size, sizeof (size), 1, file);
1269 fseek (file, secth [SECT_DATA].sh_offset, SEEK_SET);
1270 fwrite (data_section->data, data_section->cur_offset, 1, file);
1272 fseek (file, secth [SECT_SHSTRTAB].sh_offset, SEEK_SET);
1273 fwrite (sh_str_table.data->str, sh_str_table.data->len, 1, file);
1274 fseek (file, secth [SECT_SYMTAB].sh_offset, SEEK_SET);
1275 fwrite (symtab, sizeof (ElfSymbol) * num_local_syms, 1, file);
1276 fseek (file, secth [SECT_STRTAB].sh_offset, SEEK_SET);
1277 fwrite (str_table.data->str, str_table.data->len, 1, file);
1278 /*g_print ("file_offset %d vs %d\n", file_offset, ftell (file));*/
1279 /*g_assert (file_offset >= ftell (file));*/
1280 fseek (file, file_offset, SEEK_SET);
1281 fwrite (§h, sizeof (secth), 1, file);
1283 rename (tmp_outfile_name, outfile_name);
1285 g_free (tmp_outfile_name);
1286 g_free (outfile_name);
1291 #endif /* USE_ELF_WRITER */
1296 emit_start (MonoAotCompile *acfg)
1298 if (acfg->aot_opts.asm_only) {
1299 if (acfg->aot_opts.outfile)
1300 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1302 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
1303 acfg->fp = fopen (acfg->tmpfname, "w+");
1305 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
1306 acfg->fp = fdopen (i, "w+");
1308 g_assert (acfg->fp);
1312 emit_unset_mode (MonoAotCompile *acfg)
1314 if (acfg->mode == EMIT_NONE)
1316 fprintf (acfg->fp, "\n");
1317 acfg->mode = EMIT_NONE;
1321 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
1323 emit_unset_mode (acfg);
1324 #if defined(PLATFORM_WIN32)
1325 fprintf (acfg->fp, ".section %s\n", section_name);
1326 #elif defined(__MACH__)
1327 if (strcmp(section_name, ".bss") == 0)
1328 fprintf (acfg->fp, "%s\n", ".data");
1330 fprintf (acfg->fp, "%s\n", section_name);
1331 #elif defined(sparc) || defined(__arm__)
1332 /* For solaris as, GNU as should accept the same */
1333 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1335 fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1340 emit_symbol_type (MonoAotCompile *acfg, const char *name, gboolean func)
1349 emit_unset_mode (acfg);
1350 #if defined(__MACH__)
1352 #elif defined(sparc) || defined(__arm__)
1353 fprintf (acfg->fp, "\t.type %s,#%s\n", name, stype);
1354 #elif defined(PLATFORM_WIN32)
1356 #elif defined(__x86_64__) || defined(__i386__)
1357 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1359 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1364 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
1366 emit_unset_mode (acfg);
1367 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1368 // mach-o always uses a '_' prefix.
1369 fprintf (acfg->fp, "\t.globl _%s\n", name);
1371 fprintf (acfg->fp, "\t.globl %s\n", name);
1374 emit_symbol_type (acfg, name, func);
1378 emit_label (MonoAotCompile *acfg, const char *name)
1380 emit_unset_mode (acfg);
1381 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1382 // mach-o always uses a '_' prefix.
1383 fprintf (acfg->fp, "_%s:\n", name);
1385 fprintf (acfg->fp, "%s:\n", name);
1388 #if defined(PLATFORM_WIN32)
1389 /* Emit a normal label too */
1390 fprintf (acfg->fp, "%s:\n", name);
1395 emit_string (MonoAotCompile *acfg, const char *value)
1397 emit_unset_mode (acfg);
1398 fprintf (acfg->fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
1402 emit_line (MonoAotCompile *acfg)
1404 emit_unset_mode (acfg);
1405 fprintf (acfg->fp, "\n");
1409 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
1411 emit_unset_mode (acfg);
1412 emit_section_change (acfg, ".text", 1);
1413 emit_global (acfg, name, FALSE);
1414 emit_label (acfg, name);
1415 emit_string (acfg, value);
1419 emit_alignment (MonoAotCompile *acfg, int size)
1421 emit_unset_mode (acfg);
1422 #if defined(__arm__)
1423 fprintf (acfg->fp, "\t.align %d\n", ilog2 (size));
1424 #elif defined(__ppc__) && defined(__MACH__)
1425 // the mach-o assembler specifies alignments as powers of 2.
1426 fprintf (acfg->fp, "\t.align %d\t; ilog2\n", ilog2(size));
1427 #elif defined(__powerpc__)
1428 /* ignore on linux/ppc */
1430 fprintf (acfg->fp, "\t.align %d\n", size);
1435 emit_pointer (MonoAotCompile *acfg, const char *target)
1437 emit_unset_mode (acfg);
1438 emit_alignment (acfg, sizeof (gpointer));
1439 #if defined(__x86_64__)
1440 fprintf (acfg->fp, "\t.quad %s\n", target ? target : "0");
1441 #elif defined(sparc) && SIZEOF_VOID_P == 8
1442 fprintf (acfg->fp, "\t.xword %s\n", target ? target : "0");
1444 fprintf (acfg->fp, "\t.long %s\n", target ? target : "0");
1448 static char *byte_to_str;
1451 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
1454 if (acfg->mode != EMIT_BYTE) {
1455 acfg->mode = EMIT_BYTE;
1456 acfg->col_count = 0;
1459 if (byte_to_str == NULL) {
1460 byte_to_str = g_new0 (char, 256 * 8);
1461 for (i = 0; i < 256; ++i) {
1462 sprintf (byte_to_str + (i * 8), ",%d", i);
1466 for (i = 0; i < size; ++i, ++acfg->col_count) {
1467 if ((acfg->col_count % 32) == 0)
1468 fprintf (acfg->fp, "\n\t.byte %d", buf [i]);
1470 fputs (byte_to_str + (buf [i] * 8), acfg->fp);
1475 emit_int16 (MonoAotCompile *acfg, int value)
1477 if (acfg->mode != EMIT_WORD) {
1478 acfg->mode = EMIT_WORD;
1479 acfg->col_count = 0;
1481 if ((acfg->col_count++ % 8) == 0)
1482 #if defined(__MACH__)
1483 fprintf (acfg->fp, "\n\t.short ");
1484 #elif defined(__arm__)
1485 /* FIXME: Use .hword on other archs as well */
1486 fprintf (acfg->fp, "\n\t.hword ");
1488 fprintf (acfg->fp, "\n\t.word ");
1491 fprintf (acfg->fp, ", ");
1492 fprintf (acfg->fp, "%d", value);
1496 emit_int32 (MonoAotCompile *acfg, int value)
1498 if (acfg->mode != EMIT_LONG) {
1499 acfg->mode = EMIT_LONG;
1500 acfg->col_count = 0;
1502 if ((acfg->col_count++ % 8) == 0)
1503 fprintf (acfg->fp, "\n\t.long ");
1505 fprintf (acfg->fp, ",");
1506 fprintf (acfg->fp, "%d", value);
1510 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
1512 if (acfg->mode != EMIT_LONG) {
1513 acfg->mode = EMIT_LONG;
1514 acfg->col_count = 0;
1516 if ((acfg->col_count++ % 8) == 0)
1517 fprintf (acfg->fp, "\n\t.long ");
1519 fprintf (acfg->fp, ",");
1521 fprintf (acfg->fp, "%s - %s + %d", end, start, offset);
1522 else if (offset < 0)
1523 fprintf (acfg->fp, "%s - %s %d", end, start, offset);
1525 fprintf (acfg->fp, "%s - %s", end, start);
1529 emit_zero_bytes (MonoAotCompile *acfg, int num)
1531 emit_unset_mode (acfg);
1532 #if defined(__MACH__)
1533 fprintf (acfg->fp, "\t.space %d\n", num);
1535 fprintf (acfg->fp, "\t.skip %d\n", num);
1540 emit_writeout (MonoAotCompile *acfg)
1542 char *command, *objfile;
1543 char *outfile_name, *tmp_outfile_name;
1547 #if defined(__x86_64__)
1548 #define AS_OPTIONS "--64"
1549 #elif defined(sparc) && SIZEOF_VOID_P == 8
1550 #define AS_OPTIONS "-xarch=v9"
1552 #define AS_OPTIONS ""
1555 if (acfg->aot_opts.asm_only) {
1556 printf ("Output file: '%s'.\n", acfg->tmpfname);
1557 if (acfg->aot_opts.static_link)
1558 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1562 if (acfg->aot_opts.static_link) {
1563 if (acfg->aot_opts.outfile)
1564 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1566 objfile = g_strdup_printf ("%s.o", acfg->image->name);
1568 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
1570 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
1571 printf ("Executing the native assembler: %s\n", command);
1572 if (system (command) != 0) {
1580 if (acfg->aot_opts.static_link) {
1581 printf ("Output file: '%s'.\n", objfile);
1582 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1587 if (acfg->aot_opts.outfile)
1588 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1590 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1592 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1595 command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
1596 #elif defined(__ppc__) && defined(__MACH__)
1597 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
1598 #elif defined(PLATFORM_WIN32)
1599 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
1601 if (acfg->aot_opts.no_dlsym) {
1603 * Need to link using gcc so our ctor function gets called.
1605 command = g_strdup_printf ("gcc -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1607 command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1610 printf ("Executing the native linker: %s\n", command);
1611 if (system (command) != 0) {
1612 g_free (tmp_outfile_name);
1613 g_free (outfile_name);
1621 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
1622 printf ("Stripping the binary: %s\n", com);
1626 rename (tmp_outfile_name, outfile_name);
1628 g_free (tmp_outfile_name);
1629 g_free (outfile_name);
1632 if (acfg->aot_opts.save_temps)
1633 printf ("Retained input file.\n");
1635 unlink (acfg->tmpfname);
1640 #endif /* ASM_WRITER */
1643 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
1645 if (acfg->aot_opts.no_dlsym) {
1646 g_ptr_array_add (acfg->globals, g_strdup (name));
1648 emit_global_inner (acfg, name, func);
1653 emit_byte (MonoAotCompile *acfg, guint8 val)
1655 emit_bytes (acfg, &val, 1);
1659 mono_get_field_token (MonoClassField *field)
1661 MonoClass *klass = field->parent;
1664 for (i = 0; i < klass->field.count; ++i) {
1665 if (field == &klass->fields [i])
1666 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1669 g_assert_not_reached ();
1674 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1678 //printf ("ENCODE: %d 0x%x.\n", value, value);
1681 * Same encoding as the one used in the metadata, extended to handle values
1682 * greater than 0x1fffffff.
1684 if ((value >= 0) && (value <= 127))
1686 else if ((value >= 0) && (value <= 16383)) {
1687 p [0] = 0x80 | (value >> 8);
1688 p [1] = value & 0xff;
1690 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1691 p [0] = (value >> 24) | 0xc0;
1692 p [1] = (value >> 16) & 0xff;
1693 p [2] = (value >> 8) & 0xff;
1694 p [3] = value & 0xff;
1699 p [1] = (value >> 24) & 0xff;
1700 p [2] = (value >> 16) & 0xff;
1701 p [3] = (value >> 8) & 0xff;
1702 p [4] = value & 0xff;
1710 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1714 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1718 index = g_hash_table_size (cfg->image_hash);
1719 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1720 g_ptr_array_add (cfg->image_table, image);
1726 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1729 MonoClass *k = NULL;
1731 /* FIXME: Search referenced images as well */
1732 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1733 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1738 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1739 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1745 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1750 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1751 * standard metadata encoding.
1754 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1758 if (klass->generic_class) {
1760 g_assert (klass->type_token);
1762 /* Find a typespec for a class if possible */
1763 token = find_typespec_for_class (acfg, klass);
1765 encode_value (token, p, &p);
1766 encode_value (get_image_index (acfg, acfg->image), p, &p);
1768 MonoClass *gclass = klass->generic_class->container_class;
1769 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1772 /* Encode it ourselves */
1774 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1775 encode_value (MONO_TYPE_GENERICINST, p, &p);
1776 encode_klass_ref (acfg, gclass, p, &p);
1777 encode_value (inst->type_argc, p, &p);
1778 for (i = 0; i < inst->type_argc; ++i)
1779 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1781 } else if (klass->type_token) {
1782 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1783 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1784 encode_value (get_image_index (acfg, klass->image), p, &p);
1785 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1786 MonoGenericParam *param = klass->byval_arg.data.generic_param;
1789 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1790 encode_value (klass->byval_arg.type, p, &p);
1792 encode_value (param->num, p, &p);
1794 g_assert (param->owner);
1795 encode_value (param->owner->is_method, p, &p);
1796 if (param->owner->is_method)
1797 encode_method_ref (acfg, param->owner->owner.method, p, &p);
1799 encode_klass_ref (acfg, param->owner->owner.klass, p, &p);
1802 g_assert (klass->rank > 0);
1803 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1804 encode_value (get_image_index (acfg, klass->image), p, &p);
1805 encode_value (klass->rank, p, &p);
1806 encode_klass_ref (acfg, klass->element_class, p, &p);
1812 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1814 guint32 token = mono_get_field_token (field);
1817 encode_klass_ref (cfg, field->parent, p, &p);
1818 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1819 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1824 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1828 MonoGenericInst *inst;
1830 /* Encode the context */
1831 inst = context->class_inst;
1832 encode_value (inst ? 1 : 0, p, &p);
1834 encode_value (inst->type_argc, p, &p);
1835 for (i = 0; i < inst->type_argc; ++i)
1836 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1838 inst = context->method_inst;
1839 encode_value (inst ? 1 : 0, p, &p);
1841 encode_value (inst->type_argc, p, &p);
1842 for (i = 0; i < inst->type_argc; ++i)
1843 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1849 #define MAX_IMAGE_INDEX 250
1852 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1854 guint32 image_index = get_image_index (acfg, method->klass->image);
1855 guint32 token = method->token;
1856 MonoJumpInfoToken *ji;
1859 g_assert (image_index < MAX_IMAGE_INDEX);
1861 /* Mark methods which can't use aot trampolines because they need the further
1862 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1864 if (method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
1865 encode_value ((252 << 24), p, &p);
1867 if (method->wrapper_type) {
1869 encode_value ((253 << 24), p, &p);
1871 encode_value (method->wrapper_type, p, &p);
1873 switch (method->wrapper_type) {
1874 case MONO_WRAPPER_REMOTING_INVOKE:
1875 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1876 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1879 m = mono_marshal_method_from_wrapper (method);
1881 encode_method_ref (acfg, m, p, &p);
1884 case MONO_WRAPPER_PROXY_ISINST:
1885 case MONO_WRAPPER_LDFLD:
1886 case MONO_WRAPPER_LDFLDA:
1887 case MONO_WRAPPER_STFLD:
1888 case MONO_WRAPPER_ISINST: {
1889 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1890 encode_klass_ref (acfg, proxy_class, p, &p);
1893 case MONO_WRAPPER_LDFLD_REMOTE:
1894 case MONO_WRAPPER_STFLD_REMOTE:
1896 case MONO_WRAPPER_ALLOC: {
1897 int alloc_type = mono_gc_get_managed_allocator_type (method);
1898 g_assert (alloc_type != -1);
1899 encode_value (alloc_type, p, &p);
1902 case MONO_WRAPPER_STELEMREF:
1903 case MONO_WRAPPER_MONITOR_FAST_ENTER:
1904 case MONO_WRAPPER_MONITOR_FAST_EXIT:
1906 case MONO_WRAPPER_STATIC_RGCTX_INVOKE: {
1909 m = mono_marshal_method_from_wrapper (method);
1911 encode_method_ref (acfg, m, p, &p);
1915 g_assert_not_reached ();
1917 } else if (mono_method_signature (method)->is_inflated) {
1919 * This is a generic method, find the original token which referenced it and
1921 * Obtain the token from information recorded by the JIT.
1923 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1925 image_index = get_image_index (acfg, ji->image);
1926 g_assert (image_index < MAX_IMAGE_INDEX);
1930 encode_value ((255 << 24), p, &p);
1931 encode_value (image_index, p, &p);
1932 encode_value (token, p, &p);
1934 MonoMethod *declaring;
1935 MonoGenericContext *context = mono_method_get_context (method);
1937 g_assert (method->is_inflated);
1938 declaring = ((MonoMethodInflated*)method)->declaring;
1941 * This might be a non-generic method of a generic instance, which
1942 * doesn't have a token since the reference is generated by the JIT
1943 * like Nullable:Box/Unbox, or by generic sharing.
1947 encode_value ((254 << 24), p, &p);
1948 /* Encode the klass */
1949 encode_klass_ref (acfg, method->klass, p, &p);
1950 /* Encode the method */
1951 image_index = get_image_index (acfg, method->klass->image);
1952 g_assert (image_index < MAX_IMAGE_INDEX);
1953 g_assert (declaring->token);
1954 token = declaring->token;
1955 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1956 encode_value (image_index, p, &p);
1957 encode_value (token, p, &p);
1958 encode_generic_context (acfg, context, p, &p);
1960 } else if (token == 0) {
1961 /* This might be a method of a constructed type like int[,].Set */
1962 /* Obtain the token from information recorded by the JIT */
1963 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1965 image_index = get_image_index (acfg, ji->image);
1966 g_assert (image_index < MAX_IMAGE_INDEX);
1970 encode_value ((255 << 24), p, &p);
1971 encode_value (image_index, p, &p);
1972 encode_value (token, p, &p);
1974 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1975 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1981 compare_patches (gconstpointer a, gconstpointer b)
1985 i = (*(MonoJumpInfo**)a)->ip.i;
1986 j = (*(MonoJumpInfo**)b)->ip.i;
2000 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2003 static inline gboolean
2004 is_plt_patch (MonoJumpInfo *patch_info)
2006 switch (patch_info->type) {
2007 case MONO_PATCH_INFO_METHOD:
2008 case MONO_PATCH_INFO_INTERNAL_METHOD:
2009 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2010 case MONO_PATCH_INFO_CLASS_INIT:
2011 case MONO_PATCH_INFO_RGCTX_FETCH:
2012 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2013 case MONO_PATCH_INFO_MONITOR_ENTER:
2014 case MONO_PATCH_INFO_MONITOR_EXIT:
2022 * is_shared_got_patch:
2024 * Return whenever PATCH_INFO refers to a patch which needs a shared GOT
2026 * Keep it in sync with the version in aot-runtime.c.
2028 static inline gboolean
2029 is_shared_got_patch (MonoJumpInfo *patch_info)
2031 switch (patch_info->type) {
2032 case MONO_PATCH_INFO_VTABLE:
2033 case MONO_PATCH_INFO_CLASS:
2034 case MONO_PATCH_INFO_IID:
2035 case MONO_PATCH_INFO_ADJUSTED_IID:
2036 case MONO_PATCH_INFO_FIELD:
2037 case MONO_PATCH_INFO_SFLDA:
2038 case MONO_PATCH_INFO_DECLSEC:
2039 case MONO_PATCH_INFO_LDTOKEN:
2040 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2041 case MONO_PATCH_INFO_RVA:
2042 case MONO_PATCH_INFO_METHODCONST:
2050 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2054 if (is_plt_patch (patch_info)) {
2055 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
2060 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2062 res = acfg->plt_offset;
2063 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
2064 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
2065 acfg->plt_offset ++;
2075 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2076 * JI could be found if it exists, otherwise allocates a new one.
2079 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2083 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
2085 return got_offset - 1;
2087 got_offset = acfg->got_offset;
2088 acfg->got_offset ++;
2090 acfg->stats.got_slots ++;
2091 acfg->stats.got_slot_types [ji->type] ++;
2097 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2102 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
2103 got_offset = get_got_offset (acfg, ji);
2104 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
2105 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
2106 g_ptr_array_add (acfg->shared_patches, copy);
2109 return get_got_offset (acfg, ji);
2112 /* Add a method to the list of methods which need to be emitted */
2114 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
2116 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2117 g_ptr_array_add (acfg->methods, method);
2118 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2119 acfg->nmethods = acfg->methods->len + 1;
2124 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2126 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2134 add_method (MonoAotCompile *acfg, MonoMethod *method)
2138 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2142 index = acfg->method_index;
2143 add_method_with_index (acfg, method, index);
2145 /* FIXME: Fix quadratic behavior */
2146 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2148 acfg->method_index ++;
2154 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2158 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2161 add_method (acfg, method);
2162 g_ptr_array_add (acfg->extra_methods, method);
2166 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2168 MonoAotCompile *acfg = user_data;
2169 MonoJitICallInfo *callinfo = value;
2170 MonoMethod *wrapper;
2176 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2177 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2180 add_method (acfg, wrapper);
2184 get_runtime_invoke_sig (MonoMethodSignature *sig)
2186 MonoMethodBuilder *mb;
2189 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2190 m = mono_mb_create_method (mb, sig, 16);
2191 return mono_marshal_get_runtime_invoke (m);
2195 add_wrappers (MonoAotCompile *acfg)
2197 MonoMethod *method, *m;
2198 int i, j, nallocators;
2199 MonoMethodSignature *sig, *csig;
2203 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2204 * so there is only one wrapper of a given type, or inlining their contents into their
2209 * FIXME: This depends on the fact that different wrappers have different
2213 /* FIXME: Collect these automatically */
2215 /* Runtime invoke wrappers */
2217 /* void runtime-invoke () [.cctor] */
2218 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2219 csig->ret = &mono_defaults.void_class->byval_arg;
2220 add_method (acfg, get_runtime_invoke_sig (csig));
2222 /* void runtime-invoke () [Finalize] */
2223 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2225 csig->ret = &mono_defaults.void_class->byval_arg;
2226 add_method (acfg, get_runtime_invoke_sig (csig));
2228 /* void runtime-invoke (string) [exception ctor] */
2229 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2231 csig->ret = &mono_defaults.void_class->byval_arg;
2232 csig->params [0] = &mono_defaults.string_class->byval_arg;
2233 add_method (acfg, get_runtime_invoke_sig (csig));
2235 /* void runtime-invoke (string, string) [exception ctor] */
2236 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2238 csig->ret = &mono_defaults.void_class->byval_arg;
2239 csig->params [0] = &mono_defaults.string_class->byval_arg;
2240 csig->params [1] = &mono_defaults.string_class->byval_arg;
2241 add_method (acfg, get_runtime_invoke_sig (csig));
2243 /* string runtime-invoke () [Exception.ToString ()] */
2244 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2246 csig->ret = &mono_defaults.string_class->byval_arg;
2247 add_method (acfg, get_runtime_invoke_sig (csig));
2249 /* void runtime-invoke (string, Exception) [exception ctor] */
2250 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2252 csig->ret = &mono_defaults.void_class->byval_arg;
2253 csig->params [0] = &mono_defaults.string_class->byval_arg;
2254 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2255 add_method (acfg, get_runtime_invoke_sig (csig));
2257 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2258 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2260 csig->ret = &(mono_class_from_name (
2261 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2262 csig->params [0] = &mono_defaults.string_class->byval_arg;
2263 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2264 add_method (acfg, get_runtime_invoke_sig (csig));
2266 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2268 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2269 gboolean skip = FALSE;
2271 method = mono_get_method (acfg->image, token, NULL);
2273 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2274 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2275 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2278 if (method->is_generic || method->klass->generic_container)
2281 /* Skip methods which can not be handled by get_runtime_invoke () */
2282 sig = mono_method_signature (method);
2283 if ((sig->ret->type == MONO_TYPE_PTR) ||
2284 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2287 for (j = 0; j < sig->param_count; j++) {
2288 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2293 add_method (acfg, mono_marshal_get_runtime_invoke (method));
2296 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2297 MonoMethodDesc *desc;
2298 MonoMethod *orig_method;
2300 /* JIT icall wrappers */
2301 /* FIXME: locking */
2302 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2304 /* Managed Allocators */
2305 nallocators = mono_gc_get_managed_allocator_types ();
2306 for (i = 0; i < nallocators; ++i) {
2307 m = mono_gc_get_managed_allocator_by_type (i);
2309 add_method (acfg, m);
2313 add_method (acfg, mono_marshal_get_stelemref ());
2315 /* Monitor Enter/Exit */
2316 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2317 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2318 g_assert (orig_method);
2319 mono_method_desc_free (desc);
2320 add_method (acfg, mono_monitor_get_fast_path (orig_method));
2322 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2323 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2324 g_assert (orig_method);
2325 mono_method_desc_free (desc);
2326 add_method (acfg, mono_monitor_get_fast_path (orig_method));
2329 /* remoting-invoke wrappers */
2330 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2331 MonoMethodSignature *sig;
2333 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2334 method = mono_get_method (acfg->image, token, NULL);
2336 sig = mono_method_signature (method);
2338 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
2339 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2340 m = mono_marshal_get_remoting_invoke_with_check (method);
2342 add_method (acfg, m);
2346 /* delegate-invoke wrappers */
2347 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2350 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2351 klass = mono_class_get (acfg->image, token);
2353 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2354 method = mono_get_delegate_invoke (klass);
2356 m = mono_marshal_get_delegate_invoke (method, NULL);
2358 add_method (acfg, m);
2363 /* static rgctx wrappers */
2364 /* FIXME: Each wrapper belongs to a given instantiation of a generic method */
2365 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2366 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2367 method = mono_get_method (acfg->image, token, NULL);
2369 if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
2370 (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
2371 mono_class_generic_sharing_enabled (method->klass) &&
2372 mono_method_is_generic_sharable_impl (method, FALSE)) {
2373 m = mono_marshal_get_static_rgctx_invoke (method);
2374 add_method (acfg, m);
2381 has_type_vars (MonoClass *klass)
2383 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2386 return has_type_vars (klass->element_class);
2387 if (klass->generic_class) {
2388 MonoGenericContext *context = &klass->generic_class->context;
2389 if (context->class_inst) {
2392 for (i = 0; i < context->class_inst->type_argc; ++i)
2393 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2401 method_has_type_vars (MonoMethod *method)
2403 if (has_type_vars (method->klass))
2406 if (method->is_inflated) {
2407 MonoGenericContext *context = mono_method_get_context (method);
2408 if (context->method_inst) {
2411 for (i = 0; i < context->method_inst->type_argc; ++i)
2412 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2420 * add_generic_instances:
2422 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2425 add_generic_instances (MonoAotCompile *acfg)
2430 MonoGenericContext *context;
2432 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2433 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2434 method = mono_get_method (acfg->image, token, NULL);
2436 context = mono_method_get_context (method);
2437 if (context && ((context->class_inst && context->class_inst->is_open) ||
2438 (context->method_inst && context->method_inst->is_open)))
2441 if (method->klass->image != acfg->image)
2444 if (mono_method_is_generic_sharable_impl (method, FALSE))
2448 add_extra_method (acfg, method);
2451 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2455 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2457 klass = mono_class_get (acfg->image, token);
2460 mono_class_init (klass);
2462 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2465 if (has_type_vars (klass))
2469 * Add rgctx wrappers for cctors since those are called by the runtime, so
2470 * there is no methodspec for them. This is needed even for shared classes,
2471 * since rgctx wrappers belong to inflated methods.
2473 method = mono_class_get_cctor (klass);
2475 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
2478 while ((method = mono_class_get_methods (klass, &iter))) {
2479 if (mono_method_is_generic_sharable_impl (method, FALSE))
2483 if (method->is_generic)
2488 * FIXME: Instances which are referenced by these methods are not added,
2489 * for example Array.Resize<int> for List<int>.Add ().
2491 add_extra_method (acfg, method);
2497 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2499 int i, pindex, start_index, method_index;
2501 MonoJumpInfo *patch_info;
2502 MonoMethodHeader *header;
2503 gboolean skip, direct_call;
2505 char direct_call_target [128];
2508 header = mono_method_get_header (method);
2510 method_index = get_method_index (acfg, method);
2513 /* Collect and sort relocations */
2514 patches = g_ptr_array_new ();
2515 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2516 g_ptr_array_add (patches, patch_info);
2517 g_ptr_array_sort (patches, compare_patches);
2520 for (i = 0; i < code_len; i++) {
2522 for (pindex = start_index; pindex < patches->len; ++pindex) {
2523 patch_info = g_ptr_array_index (patches, pindex);
2524 if (patch_info->ip.i >= i)
2528 #ifdef MONO_ARCH_AOT_SUPPORTED
2530 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2531 start_index = pindex;
2533 switch (patch_info->type) {
2534 case MONO_PATCH_INFO_NONE:
2536 case MONO_PATCH_INFO_GOT_OFFSET: {
2537 guint32 offset = mono_arch_get_patch_offset (code + i);
2538 emit_bytes (acfg, code + i, offset);
2539 emit_symbol_diff (acfg, "got", ".", offset);
2541 i += offset + 4 - 1;
2546 if (!is_got_patch (patch_info->type))
2550 * If this patch is a call, try emitting a direct call instead of
2551 * through a PLT entry. This is possible if the called method is in
2552 * the same assembly and requires no initialization.
2554 direct_call = FALSE;
2555 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
2556 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2558 gboolean direct_callable = TRUE;
2560 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2561 direct_callable = FALSE;
2562 if (direct_callable) {
2563 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2565 sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
2566 patch_info->type = MONO_PATCH_INFO_NONE;
2567 acfg->stats.direct_calls ++;
2571 acfg->stats.all_calls ++;
2574 if (!got_only && !direct_call) {
2575 int plt_offset = get_plt_offset (acfg, patch_info);
2576 if (plt_offset != -1) {
2577 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2579 sprintf (direct_call_target, ".Lp_%d", plt_offset);
2581 /* Nullify the patch */
2582 patch_info->type = MONO_PATCH_INFO_NONE;
2587 #if defined(__i386__) || defined(__x86_64__)
2588 g_assert (code [i] == 0xe8);
2589 /* Need to make sure this is exactly 5 bytes long */
2590 emit_byte (acfg, '\xe8');
2591 emit_symbol_diff (acfg, direct_call_target, ".", -4);
2593 #elif defined(__arm__)
2594 #ifdef USE_BIN_WRITER
2595 /* FIXME: Can't encode this using the current symbol writer functions */
2596 g_assert_not_reached ();
2598 emit_unset_mode (acfg);
2599 fprintf (acfg->fp, "bl %s\n", direct_call_target);
2604 got_slot = get_got_offset (acfg, patch_info);
2606 emit_bytes (acfg, code + i, mono_arch_get_patch_offset (code + i));
2608 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
2609 #elif defined(__i386__)
2610 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
2611 #elif defined(__arm__)
2612 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
2614 g_assert_not_reached ();
2617 i += mono_arch_get_patch_offset (code + i) + 4 - 1;
2623 #endif /* MONO_ARCH_AOT_SUPPORTED */
2626 /* Find next patch */
2628 for (pindex = start_index; pindex < patches->len; ++pindex) {
2629 patch_info = g_ptr_array_index (patches, pindex);
2630 if (patch_info->ip.i >= i)
2634 /* Try to emit multiple bytes at once */
2635 if (pindex < patches->len && patch_info->ip.i > i) {
2636 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2637 i = patch_info->ip.i - 1;
2639 emit_bytes (acfg, code + i, 1);
2646 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2652 int func_alignment = 16;
2653 MonoMethodHeader *header;
2655 method = cfg->orig_method;
2656 code = cfg->native_code;
2657 header = mono_method_get_header (method);
2659 method_index = get_method_index (acfg, method);
2661 /* Make the labels local */
2662 sprintf (symbol, ".Lm_%x", method_index);
2664 emit_alignment (acfg, func_alignment);
2665 emit_label (acfg, symbol);
2666 if (acfg->aot_opts.write_symbols)
2667 emit_global (acfg, symbol, TRUE);
2669 if (cfg->verbose_level > 0)
2670 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2672 acfg->stats.code_size += cfg->code_len;
2674 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2676 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2684 * Encode PATCH_INFO into its disk representation.
2687 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2691 switch (patch_info->type) {
2692 case MONO_PATCH_INFO_NONE:
2694 case MONO_PATCH_INFO_IMAGE:
2695 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2697 case MONO_PATCH_INFO_METHOD_REL:
2698 encode_value ((gint)patch_info->data.offset, p, &p);
2700 case MONO_PATCH_INFO_SWITCH: {
2701 gpointer *table = (gpointer *)patch_info->data.table->table;
2704 encode_value (patch_info->data.table->table_size, p, &p);
2705 for (k = 0; k < patch_info->data.table->table_size; k++)
2706 encode_value ((int)(gssize)table [k], p, &p);
2709 case MONO_PATCH_INFO_METHODCONST:
2710 case MONO_PATCH_INFO_METHOD:
2711 case MONO_PATCH_INFO_METHOD_JUMP:
2712 case MONO_PATCH_INFO_ICALL_ADDR:
2713 case MONO_PATCH_INFO_METHOD_RGCTX:
2714 encode_method_ref (acfg, patch_info->data.method, p, &p);
2716 case MONO_PATCH_INFO_INTERNAL_METHOD:
2717 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2718 guint32 len = strlen (patch_info->data.name);
2720 encode_value (len, p, &p);
2722 memcpy (p, patch_info->data.name, len);
2727 case MONO_PATCH_INFO_LDSTR: {
2728 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2729 guint32 token = patch_info->data.token->token;
2730 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2731 encode_value (image_index, p, &p);
2732 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2735 case MONO_PATCH_INFO_RVA:
2736 case MONO_PATCH_INFO_DECLSEC:
2737 case MONO_PATCH_INFO_LDTOKEN:
2738 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2739 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2740 encode_value (patch_info->data.token->token, p, &p);
2741 encode_value (patch_info->data.token->has_context, p, &p);
2742 if (patch_info->data.token->has_context)
2743 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2745 case MONO_PATCH_INFO_EXC_NAME: {
2746 MonoClass *ex_class;
2749 mono_class_from_name (mono_defaults.exception_class->image,
2750 "System", patch_info->data.target);
2751 g_assert (ex_class);
2752 encode_klass_ref (acfg, ex_class, p, &p);
2755 case MONO_PATCH_INFO_R4:
2756 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2758 case MONO_PATCH_INFO_R8:
2759 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2760 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2762 case MONO_PATCH_INFO_VTABLE:
2763 case MONO_PATCH_INFO_CLASS:
2764 case MONO_PATCH_INFO_IID:
2765 case MONO_PATCH_INFO_ADJUSTED_IID:
2766 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2768 case MONO_PATCH_INFO_CLASS_INIT:
2769 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2770 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2772 case MONO_PATCH_INFO_FIELD:
2773 case MONO_PATCH_INFO_SFLDA:
2774 encode_field_info (acfg, patch_info->data.field, p, &p);
2776 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2778 case MONO_PATCH_INFO_RGCTX_FETCH: {
2779 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2781 encode_method_ref (acfg, entry->method, p, &p);
2782 encode_value (entry->in_mrgctx, p, &p);
2783 encode_value (entry->info_type, p, &p);
2784 encode_value (entry->data->type, p, &p);
2785 encode_patch (acfg, entry->data, p, &p);
2788 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2789 case MONO_PATCH_INFO_MONITOR_ENTER:
2790 case MONO_PATCH_INFO_MONITOR_EXIT:
2793 g_warning ("unable to handle jump info %d", patch_info->type);
2794 g_assert_not_reached ();
2801 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2804 guint32 last_offset, j, pindex;
2805 MonoJumpInfo *patch_info;
2807 encode_value (n_patches, p, &p);
2810 encode_value (first_got_offset, p, &p);
2812 /* First encode the type+position table */
2815 for (pindex = 0; pindex < patches->len; ++pindex) {
2817 patch_info = g_ptr_array_index (patches, pindex);
2819 if (patch_info->type == MONO_PATCH_INFO_NONE)
2824 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
2825 offset = patch_info->ip.i - last_offset;
2826 last_offset = patch_info->ip.i;
2828 /* Only the type is needed */
2829 *p = patch_info->type;
2833 /* Then encode the other info */
2834 for (pindex = 0; pindex < patches->len; ++pindex) {
2835 patch_info = g_ptr_array_index (patches, pindex);
2837 if (is_shared_got_patch (patch_info)) {
2838 guint32 offset = get_got_offset (acfg, patch_info);
2839 encode_value (offset, p, &p);
2841 encode_patch (acfg, patch_info, p, &p);
2849 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2853 int pindex, buf_size, n_patches;
2857 MonoJumpInfo *patch_info;
2858 MonoMethodHeader *header;
2859 guint32 method_index;
2861 guint32 first_got_offset;
2863 method = cfg->orig_method;
2864 code = cfg->native_code;
2865 header = mono_method_get_header (method);
2867 method_index = get_method_index (acfg, method);
2869 /* Make the labels local */
2870 sprintf (symbol, ".Lm_%x_p", method_index);
2872 /* Sort relocations */
2873 patches = g_ptr_array_new ();
2874 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2875 g_ptr_array_add (patches, patch_info);
2876 g_ptr_array_sort (patches, compare_patches);
2878 first_got_offset = acfg->cfgs [method_index]->got_offset;
2880 /**********************/
2881 /* Encode method info */
2882 /**********************/
2884 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2885 p = buf = g_malloc (buf_size);
2887 if (mono_class_get_cctor (method->klass))
2888 encode_klass_ref (acfg, method->klass, p, &p);
2890 /* Not needed when loading the method */
2891 encode_value (0, p, &p);
2894 if (cfg->opt & MONO_OPT_SHARED) {
2895 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2896 for (l = cfg->ldstr_list; l; l = l->next) {
2897 encode_value ((long)l->data, p, &p);
2901 /* Used only in shared mode */
2902 g_assert (!cfg->ldstr_list);
2905 for (pindex = 0; pindex < patches->len; ++pindex) {
2906 patch_info = g_ptr_array_index (patches, pindex);
2908 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2909 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2910 patch_info->type = MONO_PATCH_INFO_NONE;
2915 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2916 /* Stored in a GOT slot initialized at module load time */
2917 patch_info->type = MONO_PATCH_INFO_NONE;
2921 if (is_plt_patch (patch_info)) {
2922 /* Calls are made through the PLT */
2923 patch_info->type = MONO_PATCH_INFO_NONE;
2931 g_assert (cfg->has_got_slots);
2933 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2935 acfg->stats.info_size += p - buf;
2937 /* Emit method info */
2939 emit_label (acfg, symbol);
2941 g_assert (p - buf < buf_size);
2942 emit_bytes (acfg, buf, p - buf);
2947 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2950 int k, buf_size, method_index;
2951 guint32 debug_info_size;
2954 MonoMethodHeader *header;
2955 guint8 *p, *buf, *debug_info;
2956 MonoJitInfo *jinfo = cfg->jit_info;
2958 method = cfg->orig_method;
2959 code = cfg->native_code;
2960 header = mono_method_get_header (method);
2962 method_index = get_method_index (acfg, method);
2964 /* Make the labels local */
2965 sprintf (symbol, ".Le_%x_p", method_index);
2967 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2969 buf_size = header->num_clauses * 256 + debug_info_size + 128;
2970 p = buf = g_malloc (buf_size);
2972 encode_value (jinfo->code_size, p, &p);
2973 encode_value (jinfo->used_regs, p, &p);
2974 encode_value (jinfo->has_generic_jit_info, p, &p);
2976 /* Exception table */
2977 if (header->num_clauses) {
2978 for (k = 0; k < header->num_clauses; ++k) {
2979 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2981 encode_value (ei->exvar_offset, p, &p);
2983 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2984 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2986 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2987 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2988 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2992 if (jinfo->has_generic_jit_info) {
2993 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2995 encode_value (gi->has_this ? 1 : 0, p, &p);
2996 encode_value (gi->this_reg, p, &p);
2997 encode_value (gi->this_offset, p, &p);
3000 * Need to encode jinfo->method too, since it is not equal to 'method'
3001 * when using generic sharing.
3003 encode_method_ref (acfg, jinfo->method, p, &p);
3006 g_assert (debug_info_size < buf_size);
3008 encode_value (debug_info_size, p, &p);
3009 if (debug_info_size) {
3010 memcpy (p, debug_info, debug_info_size);
3011 p += debug_info_size;
3012 g_free (debug_info);
3015 acfg->stats.ex_info_size += p - buf;
3019 emit_label (acfg, symbol);
3021 g_assert (p - buf < buf_size);
3022 emit_bytes (acfg, buf, p - buf);
3027 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3029 MonoClass *klass = mono_class_get (acfg->image, token);
3033 gboolean no_special_static, cant_encode;
3034 gpointer iter = NULL;
3036 buf_size = 10240 + (klass->vtable_size * 16);
3037 p = buf = g_malloc (buf_size);
3041 mono_class_init (klass);
3043 mono_class_get_nested_types (klass, &iter);
3044 g_assert (klass->nested_classes_inited);
3046 mono_class_setup_vtable (klass);
3049 * Emit all the information which is required for creating vtables so
3050 * the runtime does not need to create the MonoMethod structures which
3051 * take up a lot of space.
3054 no_special_static = !mono_class_has_special_static_fields (klass);
3056 /* Check whenever we have enough info to encode the vtable */
3057 cant_encode = FALSE;
3058 for (i = 0; i < klass->vtable_size; ++i) {
3059 MonoMethod *cm = klass->vtable [i];
3061 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3065 if (klass->generic_container || cant_encode) {
3066 encode_value (-1, p, &p);
3068 encode_value (klass->vtable_size, p, &p);
3069 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);
3070 if (klass->has_cctor)
3071 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3072 if (klass->has_finalize)
3073 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3075 encode_value (klass->instance_size, p, &p);
3076 encode_value (mono_class_data_size (klass), p, &p);
3077 encode_value (klass->packing_size, p, &p);
3078 encode_value (klass->min_align, p, &p);
3080 for (i = 0; i < klass->vtable_size; ++i) {
3081 MonoMethod *cm = klass->vtable [i];
3084 encode_method_ref (acfg, cm, p, &p);
3086 encode_value (0, p, &p);
3090 acfg->stats.class_info_size += p - buf;
3093 sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
3094 emit_label (acfg, symbol);
3096 g_assert (p - buf < buf_size);
3097 emit_bytes (acfg, buf, p - buf);
3102 * Calls made from AOTed code are routed through a table of jumps similar to the
3103 * ELF PLT (Program Linkage Table). The differences are the following:
3104 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3105 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3106 * jumps. This means the jumps need to be patched when the address of the callee is
3107 * known. Initially the PLT entries jump to code which transfers control to the
3108 * AOT runtime through the first PLT entry.
3111 emit_plt (MonoAotCompile *acfg)
3116 guint32 *plt_info_offsets;
3119 * Encode info need to resolve PLT entries.
3121 buf_size = acfg->plt_offset * 128;
3122 p = buf = g_malloc (buf_size);
3124 plt_info_offsets = g_new0 (guint32, acfg->plt_offset);
3126 for (i = 1; i < acfg->plt_offset; ++i) {
3127 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3129 plt_info_offsets [i] = p - buf;
3130 encode_value (patch_info->type, p, &p);
3131 encode_patch (acfg, patch_info, p, &p);
3135 sprintf (symbol, "plt");
3137 emit_section_change (acfg, ".text", 0);
3138 emit_global (acfg, symbol, TRUE);
3140 /* This section will be made read-write by the AOT loader */
3141 emit_alignment (acfg, PAGESIZE);
3143 emit_label (acfg, symbol);
3145 #if defined(USE_BIN_WRITER) && defined(__arm__)
3147 g_assert_not_reached ();
3150 for (i = 0; i < acfg->plt_offset; ++i) {
3153 sprintf (label, ".Lp_%d", i);
3154 emit_label (acfg, label);
3157 * The first plt entry is used to transfer code to the AOT loader.
3160 #if defined(__i386__)
3162 /* It is filled up during loading by the AOT loader. */
3163 emit_zero_bytes (acfg, 16);
3165 /* Need to make sure this is 9 bytes long */
3166 emit_byte (acfg, '\xe9');
3167 emit_symbol_diff (acfg, "plt", ".", -4);
3168 emit_int32 (acfg, plt_info_offsets [i]);
3170 #elif defined(__x86_64__)
3172 * We can't emit jumps because they are 32 bits only so they can't be patched.
3173 * So we emit a jump table instead whose entries are patched by the AOT loader to
3174 * point to .Lpd entries. ELF stores these in the GOT too, but we don't, since
3175 * methods with GOT entries can't be called directly.
3176 * We also emit the default PLT code here since the PLT code will not be patched.
3177 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
3179 /* jmpq *<offset>(%rip) */
3180 emit_byte (acfg, '\xff');
3181 emit_byte (acfg, '\x25');
3182 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)) -4);
3183 /* Used by mono_aot_get_plt_info_offset */
3184 emit_int32 (acfg, plt_info_offsets [i]);
3185 #elif defined(__arm__)
3187 * - optimize OP_AOTCONST implementation
3188 * - optimize the PLT entries
3189 * - optimize SWITCH AOT implementation
3190 * - implement IMT support
3192 emit_unset_mode (acfg);
3193 fprintf (acfg->fp, "\tldr ip, [pc, #4]\n");
3194 fprintf (acfg->fp, "\tadd ip, pc, ip\n");
3195 fprintf (acfg->fp, "\tldr pc, [ip, #0]\n");
3196 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)));
3197 /* Used by mono_aot_get_plt_info_offset */
3198 #if defined(__MACH__)
3199 fprintf (acfg->fp, "\n\t.long %d\n", plt_info_offsets [i]);
3201 fprintf (acfg->fp, "\n\t.word %d\n", plt_info_offsets [i]);
3205 g_assert_not_reached ();
3209 g_free (plt_info_offsets);
3211 sprintf (symbol, "plt_end");
3212 emit_global (acfg, symbol, TRUE);
3213 emit_label (acfg, symbol);
3216 sprintf (symbol, "plt_info");
3217 emit_global (acfg, symbol, FALSE);
3218 emit_label (acfg, symbol);
3220 g_assert (p - buf < buf_size);
3221 emit_bytes (acfg, buf, p - buf);
3224 sprintf (symbol, "plt_jump_table_addr");
3225 emit_section_change (acfg, ".data", 0);
3226 emit_global (acfg, symbol, FALSE);
3227 emit_alignment (acfg, 8);
3228 emit_label (acfg, symbol);
3229 emit_pointer (acfg, "plt_jump_table");
3231 sprintf (symbol, "plt_jump_table_size");
3232 emit_section_change (acfg, ".data", 0);
3233 emit_global (acfg, symbol, FALSE);
3234 emit_alignment (acfg, 8);
3235 emit_label (acfg, symbol);
3236 emit_symbol_diff (acfg, "plt_jump_table_end", "plt_jump_table", 0);
3238 /* Don't make this a global so accesses don't need relocations */
3239 sprintf (symbol, "plt_jump_table");
3240 emit_section_change (acfg, ".bss", 0);
3241 emit_label (acfg, symbol);
3243 #if defined(__x86_64__) || defined(__arm__)
3244 emit_zero_bytes (acfg, (int)(acfg->plt_offset * sizeof (gpointer)));
3247 sprintf (symbol, "plt_jump_table_end");
3248 emit_label (acfg, symbol);
3251 static G_GNUC_UNUSED void
3252 emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code,
3253 guint32 code_size, int got_offset, MonoJumpInfo *ji)
3257 MonoJumpInfo *patch_info;
3263 sprintf (symbol, "%s", name);
3265 emit_section_change (acfg, ".text", 0);
3266 emit_global (acfg, symbol, TRUE);
3267 emit_alignment (acfg, 16);
3268 emit_label (acfg, symbol);
3271 * The code should access everything through the GOT, so we pass
3274 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3278 /* Sort relocations */
3279 patches = g_ptr_array_new ();
3280 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3281 g_ptr_array_add (patches, patch_info);
3282 g_ptr_array_sort (patches, compare_patches);
3284 buf_size = patches->len * 128 + 128;
3285 buf = g_malloc (buf_size);
3288 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3289 g_assert (p - buf < buf_size);
3291 sprintf (symbol, "%s_p", name);
3293 emit_section_change (acfg, ".text", 0);
3294 emit_global (acfg, symbol, FALSE);
3295 emit_label (acfg, symbol);
3297 emit_bytes (acfg, buf, p - buf);
3301 * When running in aot-only mode, we can't create trampolines at runtime, so we create
3302 * a few, and save them in the AOT file. Normal trampolines embed their argument as a
3303 * literal inside the trampoline code, we can't do that here, so instead we embed an offset
3304 * which needs to be added to the trampoline address to get the address of the GOT slot
3305 * which contains the argument value.
3306 * The generated trampolines jump to the generic trampolines using another GOT slot, which
3307 * will be setup by the AOT loader to point to the generic trampoline code of the given
3311 emit_trampolines (MonoAotCompile *acfg)
3315 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3322 if (!acfg->aot_opts.full_aot)
3325 g_assert (acfg->image->assembly);
3327 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3328 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3329 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3331 * Emit the generic trampolines.
3333 * We could save some code by treating the generic trampolines as a wrapper
3334 * method, but that approach has its own complexities, so we choose the simpler
3337 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3338 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, TRUE);
3340 /* Emit trampoline code */
3342 sprintf (symbol, "generic_trampoline_%d", tramp_type);
3344 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3347 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3348 emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL);
3350 /* Emit the exception related code pieces */
3351 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3352 emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji);
3353 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3354 emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji);
3355 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3356 emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji);
3357 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3358 emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji);
3359 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3360 emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji);
3361 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3362 emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji);
3365 for (i = 0; i < 128; ++i) {
3368 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3369 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3370 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3371 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3373 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3374 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3375 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3376 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3382 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3386 /* Reserve some entries at the end of the GOT for our use */
3387 acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
3389 sprintf (symbol, "trampolines");
3391 emit_section_change (acfg, ".text", 0);
3392 emit_global (acfg, symbol, TRUE);
3393 emit_alignment (acfg, 16);
3394 emit_label (acfg, symbol);
3396 for (i = 0; i < acfg->num_aot_trampolines; ++i) {
3397 offset = acfg->got_offset + (i * 2);
3400 * The trampolines created here are variations of the specific
3401 * trampolines created in mono_arch_create_specific_trampoline (). The
3403 * - the generic trampoline address is taken from a got slot.
3404 * - the offset of the got slot where the trampoline argument is stored
3405 * is embedded in the instruction stream, and the generic trampoline
3406 * can load the argument by loading the offset, adding it to the
3407 * address of the trampoline to get the address of the got slot, and
3408 * loading the argument from the there.
3410 #if defined(__x86_64__)
3411 /* This should be exactly 16 bytes long */
3412 /* It should work together with the generic trampoline code in tramp-amd64.c */
3413 /* call *<offset>(%rip) */
3414 emit_byte (acfg, '\x41');
3415 emit_byte (acfg, '\xff');
3416 emit_byte (acfg, '\x15');
3417 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
3418 /* This should be relative to the start of the trampoline */
3419 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
3420 emit_zero_bytes (acfg, 5);
3421 #elif defined(__arm__)
3425 /* Generate the trampoline code */
3426 /* This should be exactly 28 bytes long */
3429 ARM_PUSH (code, 0x5fff);
3430 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
3431 /* Load the value from the GOT */
3432 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
3434 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
3435 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
3437 g_assert (code - buf == 20);
3440 emit_bytes (acfg, buf, code - buf);
3441 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
3442 emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
3445 g_assert_not_reached ();
3450 /* Unbox trampolines */
3452 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3454 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3456 char call_target [256];
3458 method = mono_get_method (acfg->image, token, NULL);
3460 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3461 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
3464 sprintf (symbol, "unbox_trampoline_%d", i);
3466 emit_section_change (acfg, ".text", 0);
3467 emit_global (acfg, symbol, TRUE);
3468 emit_label (acfg, symbol);
3470 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
3472 #if defined(__x86_64__)
3477 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (cfg->orig_method), cfg->generic_sharing_context, NULL);
3479 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
3481 emit_bytes (acfg, buf, code - buf);
3483 emit_byte (acfg, '\xe9');
3484 emit_symbol_diff (acfg, call_target, ".", -4);
3486 #elif defined(__arm__)
3493 if (MONO_TYPE_ISSTRUCT (mono_method_signature (cfg->orig_method)->ret))
3496 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
3498 emit_bytes (acfg, buf, code - buf);
3499 /* jump to method */
3500 #if defined(USE_BIN_WRITER)
3502 g_assert_not_reached ();
3504 fprintf (acfg->fp, "\n\tb %s\n", call_target);
3507 g_assert_not_reached ();
3511 sprintf (symbol, "trampolines_info");
3513 emit_section_change (acfg, ".text", 0);
3514 emit_global (acfg, symbol, TRUE);
3515 emit_alignment (acfg, PAGESIZE);
3516 emit_label (acfg, symbol);
3518 emit_int32 (acfg, acfg->num_aot_trampolines);
3519 emit_int32 (acfg, acfg->got_offset);
3523 str_begins_with (const char *str1, const char *str2)
3525 int len = strlen (str2);
3526 return strncmp (str1, str2, len) == 0;
3530 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3532 gchar **args, **ptr;
3534 memset (opts, 0, sizeof (*opts));
3536 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3537 for (ptr = args; ptr && *ptr; ptr ++) {
3538 const char *arg = *ptr;
3540 if (str_begins_with (arg, "outfile=")) {
3541 opts->outfile = g_strdup (arg + strlen ("outfile="));
3542 } else if (str_begins_with (arg, "save-temps")) {
3543 opts->save_temps = TRUE;
3544 } else if (str_begins_with (arg, "keep-temps")) {
3545 opts->save_temps = TRUE;
3546 } else if (str_begins_with (arg, "write-symbols")) {
3547 opts->write_symbols = TRUE;
3548 } else if (str_begins_with (arg, "metadata-only")) {
3549 opts->metadata_only = TRUE;
3550 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3551 opts->bind_to_runtime_version = TRUE;
3552 } else if (str_begins_with (arg, "full")) {
3553 opts->full_aot = TRUE;
3555 * The no-dlsym option is only useful on the iphone, and even there,
3556 * do to other limitations of the dynamic linker, it doesn't seem to
3557 * work. So disable it for now so we don't have to support it.
3560 } else if (str_begins_with (arg, "no-dlsym")) {
3561 opts->no_dlsym = TRUE;
3563 } else if (str_begins_with (arg, "threads=")) {
3564 opts->nthreads = atoi (arg + strlen ("threads="));
3565 } else if (str_begins_with (arg, "static")) {
3566 opts->static_link = TRUE;
3567 opts->no_dlsym = TRUE;
3568 } else if (str_begins_with (arg, "asmonly")) {
3569 opts->asm_only = TRUE;
3571 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3580 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3582 MonoMethod *method = (MonoMethod*)key;
3583 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3584 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3585 MonoAotCompile *acfg = user_data;
3587 new_ji->image = ji->image;
3588 new_ji->token = ji->token;
3589 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3595 * AOT compile a given method.
3596 * This function might be called by multiple threads, so it must be thread-safe.
3599 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3602 MonoJumpInfo *patch_info;
3605 MonoMethod *wrapped;
3607 if (acfg->aot_opts.metadata_only)
3610 mono_acfg_lock (acfg);
3611 index = get_method_index (acfg, method);
3612 mono_acfg_unlock (acfg);
3614 /* fixme: maybe we can also precompile wrapper methods */
3615 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3616 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3617 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3618 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3622 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3625 wrapped = mono_marshal_method_from_wrapper (method);
3626 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3627 // FIXME: The wrapper should be generic too, but it is not
3630 InterlockedIncrement (&acfg->stats.mcount);
3632 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3634 * FIXME: Enabling this causes virtual-sync.exe to fail, since the trampoline
3635 * code can't determine that it needs to insert a sync wrapper in the AOT case.
3641 if (method->is_generic || method->klass->generic_container) {
3642 InterlockedIncrement (&acfg->stats.genericcount);
3647 if (acfg->aot_opts.full_aot)
3648 mono_use_imt = FALSE;
3651 * Since these methods are the only ones which are compiled with
3652 * AOT support, and they are not used by runtime startup/shutdown code,
3653 * the runtime will not see AOT methods during AOT compilation,so it
3654 * does not need to support them by creating a fake GOT etc.
3656 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3657 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3658 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3659 InterlockedIncrement (&acfg->stats.genericcount);
3662 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3663 /* Let the exception happen at runtime */
3667 if (cfg->disable_aot) {
3668 //printf ("Skip (other): %s\n", mono_method_full_name (method, TRUE));
3669 InterlockedIncrement (&acfg->stats.ocount);
3670 mono_destroy_compile (cfg);
3674 /* Nullify patches which need no aot processing */
3675 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3676 switch (patch_info->type) {
3677 case MONO_PATCH_INFO_LABEL:
3678 case MONO_PATCH_INFO_BB:
3679 patch_info->type = MONO_PATCH_INFO_NONE;
3686 /* Collect method->token associations from the cfg */
3687 mono_acfg_lock (acfg);
3688 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3689 mono_acfg_unlock (acfg);
3692 * Check for absolute addresses.
3695 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3696 switch (patch_info->type) {
3697 case MONO_PATCH_INFO_ABS:
3698 /* unable to handle this */
3699 //printf ("Skip (abs addr): %s %d\n", mono_method_full_name (method, TRUE), patch_info->type);
3708 InterlockedIncrement (&acfg->stats.abscount);
3709 mono_destroy_compile (cfg);
3714 * Check for wrapper methods we can't encode.
3717 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3718 if ((patch_info->type == MONO_PATCH_INFO_METHODCONST) || (patch_info->type == MONO_PATCH_INFO_METHOD)) {
3719 switch (patch_info->data.method->wrapper_type) {
3720 case MONO_WRAPPER_NONE:
3721 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3722 case MONO_WRAPPER_XDOMAIN_INVOKE:
3723 case MONO_WRAPPER_STFLD:
3724 case MONO_WRAPPER_LDFLD:
3725 case MONO_WRAPPER_LDFLDA:
3726 case MONO_WRAPPER_LDFLD_REMOTE:
3727 case MONO_WRAPPER_STFLD_REMOTE:
3728 case MONO_WRAPPER_STELEMREF:
3729 case MONO_WRAPPER_ISINST:
3730 case MONO_WRAPPER_PROXY_ISINST:
3731 case MONO_WRAPPER_ALLOC:
3732 case MONO_WRAPPER_REMOTING_INVOKE:
3733 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
3734 case MONO_WRAPPER_MONITOR_FAST_ENTER:
3735 case MONO_WRAPPER_MONITOR_FAST_EXIT:
3738 /* unable to handle this */
3739 //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));
3743 } else if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH) {
3744 MonoJumpInfo *child = patch_info->data.rgctx_entry->data;
3746 if (child->type == MONO_PATCH_INFO_METHODCONST) {
3747 switch (child->data.method->wrapper_type) {
3748 case MONO_WRAPPER_NONE:
3749 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
3759 InterlockedIncrement (&acfg->stats.wrappercount);
3760 mono_destroy_compile (cfg);
3764 /* Lock for the rest of the code */
3765 mono_acfg_lock (acfg);
3768 * Check for methods/klasses we can't encode.
3771 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3772 switch (patch_info->type) {
3773 case MONO_PATCH_INFO_METHOD:
3774 case MONO_PATCH_INFO_METHODCONST:
3775 if (patch_info->data.method->wrapper_type)
3777 if (!patch_info->data.method->token) {
3778 /* The method is part of a constructed type like Int[,].Set (). */
3779 if (!g_hash_table_lookup (acfg->token_info_hash, patch_info->data.method))
3783 case MONO_PATCH_INFO_VTABLE:
3784 case MONO_PATCH_INFO_CLASS_INIT:
3785 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3786 case MONO_PATCH_INFO_CLASS:
3787 case MONO_PATCH_INFO_IID:
3788 case MONO_PATCH_INFO_ADJUSTED_IID:
3789 if (!patch_info->data.klass->type_token)
3790 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))
3799 acfg->stats.ocount++;
3800 mono_destroy_compile (cfg);
3801 mono_acfg_unlock (acfg);
3805 /* Adds generic instances referenced by this method */
3806 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3807 switch (patch_info->type) {
3808 case MONO_PATCH_INFO_METHOD: {
3809 MonoMethod *m = patch_info->data.method;
3810 if (m->is_inflated) {
3811 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3812 mono_method_is_generic_sharable_impl (m, FALSE)) &&
3813 !method_has_type_vars (m))
3814 add_extra_method (acfg, m);
3823 /* Determine whenever the method has GOT slots */
3824 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3825 switch (patch_info->type) {
3826 case MONO_PATCH_INFO_GOT_OFFSET:
3827 case MONO_PATCH_INFO_NONE:
3829 case MONO_PATCH_INFO_IMAGE:
3830 /* The assembly is stored in GOT slot 0 */
3831 if (patch_info->data.image != acfg->image)
3832 cfg->has_got_slots = TRUE;
3835 if (!is_plt_patch (patch_info))
3836 cfg->has_got_slots = TRUE;
3841 if (!cfg->has_got_slots)
3842 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3844 /* Make a copy of the patch info which is in the mempool */
3846 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3848 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3849 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3852 patches = new_patch_info;
3854 patches_end->next = new_patch_info;
3855 patches_end = new_patch_info;
3857 cfg->patch_info = patches;
3860 /* Free some fields used by cfg to conserve memory */
3861 mono_mempool_destroy (cfg->mempool);
3862 cfg->mempool = NULL;
3863 g_free (cfg->varinfo);
3864 cfg->varinfo = NULL;
3868 mono_regstate_free (cfg->rs);
3872 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
3874 while (index >= acfg->cfgs_size) {
3875 MonoCompile **new_cfgs;
3878 new_size = acfg->cfgs_size * 2;
3879 new_cfgs = g_new0 (MonoCompile*, new_size);
3880 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3881 g_free (acfg->cfgs);
3882 acfg->cfgs = new_cfgs;
3883 acfg->cfgs_size = new_size;
3885 acfg->cfgs [index] = cfg;
3887 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3889 if (cfg->orig_method->wrapper_type)
3890 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3892 mono_acfg_unlock (acfg);
3894 InterlockedIncrement (&acfg->stats.ccount);
3898 compile_thread_main (gpointer *user_data)
3900 MonoDomain *domain = user_data [0];
3901 MonoAotCompile *acfg = user_data [1];
3902 GPtrArray *methods = user_data [2];
3905 mono_thread_attach (domain);
3907 for (i = 0; i < methods->len; ++i)
3908 compile_method (acfg, g_ptr_array_index (methods, i));
3912 load_profile_files (MonoAotCompile *acfg)
3916 int file_index, res, method_index, i;
3923 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);
3925 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3930 infile = fopen (tmp, "r");
3933 printf ("Using profile data file '%s'\n", tmp);
3938 res = fscanf (infile, "%32s\n", ver);
3939 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3940 printf ("Profile file has wrong version or invalid.\n");
3946 res = fscanf (infile, "%d\n", &token);
3950 method_index = mono_metadata_token_index (token) - 1;
3952 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3953 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3958 /* Add missing methods */
3960 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3961 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3962 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3964 unordered = g_list_reverse (unordered);
3965 if (acfg->method_order)
3966 g_list_last (acfg->method_order)->next = unordered;
3968 acfg->method_order = unordered;
3974 * Collect all patches which have shared GOT entries and alloc entries for them. The
3975 * rest will get entries allocated during emit_code ().
3978 alloc_got_slots (MonoAotCompile *acfg)
3984 /* Slot 0 is reserved for the address of the current assembly */
3985 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3986 ji->type = MONO_PATCH_INFO_IMAGE;
3987 ji->data.image = acfg->image;
3989 get_shared_got_offset (acfg, ji);
3991 for (l = acfg->method_order; l != NULL; l = l->next) {
3992 i = GPOINTER_TO_UINT (l->data);
3994 if (acfg->cfgs [i]) {
3995 MonoCompile *cfg = acfg->cfgs [i];
3997 for (ji = cfg->patch_info; ji; ji = ji->next) {
3998 if (is_shared_got_patch (ji))
3999 get_shared_got_offset (acfg, ji);
4006 emit_code (MonoAotCompile *acfg)
4012 sprintf (symbol, "methods");
4013 emit_section_change (acfg, ".text", 0);
4014 emit_global (acfg, symbol, TRUE);
4015 emit_alignment (acfg, 8);
4016 emit_label (acfg, symbol);
4018 for (l = acfg->method_order; l != NULL; l = l->next) {
4019 i = GPOINTER_TO_UINT (l->data);
4022 emit_method_code (acfg, acfg->cfgs [i]);
4025 sprintf (symbol, "methods_end");
4026 emit_section_change (acfg, ".text", 0);
4027 emit_global (acfg, symbol, FALSE);
4028 emit_alignment (acfg, 8);
4029 emit_label (acfg, symbol);
4031 sprintf (symbol, "method_offsets");
4032 emit_section_change (acfg, ".text", 1);
4033 emit_global (acfg, symbol, FALSE);
4034 emit_alignment (acfg, 8);
4035 emit_label (acfg, symbol);
4037 for (i = 0; i < acfg->nmethods; ++i) {
4038 if (acfg->cfgs [i]) {
4039 sprintf (symbol, ".Lm_%x", i);
4040 emit_symbol_diff (acfg, symbol, "methods", 0);
4042 emit_int32 (acfg, 0xffffffff);
4049 emit_info (MonoAotCompile *acfg)
4055 /* Emit method info */
4056 sprintf (symbol, "method_info");
4057 emit_section_change (acfg, ".text", 1);
4058 emit_global (acfg, symbol, FALSE);
4059 emit_alignment (acfg, 8);
4060 emit_label (acfg, symbol);
4062 /* To reduce size of generated assembly code */
4063 sprintf (symbol, "mi");
4064 emit_label (acfg, symbol);
4066 for (l = acfg->method_order; l != NULL; l = l->next) {
4067 i = GPOINTER_TO_UINT (l->data);
4070 emit_method_info (acfg, acfg->cfgs [i]);
4073 sprintf (symbol, "method_info_offsets");
4074 emit_section_change (acfg, ".text", 1);
4075 emit_global (acfg, symbol, FALSE);
4076 emit_alignment (acfg, 8);
4077 emit_label (acfg, symbol);
4079 for (i = 0; i < acfg->nmethods; ++i) {
4080 if (acfg->cfgs [i]) {
4081 sprintf (symbol, ".Lm_%x_p", i);
4082 emit_symbol_diff (acfg, symbol, "mi", 0);
4084 emit_int32 (acfg, 0);
4090 typedef struct HashEntry {
4091 guint32 key, value, index;
4092 struct HashEntry *next;
4096 * emit_extra_methods:
4098 * Emit methods which are not in the METHOD table, like wrappers.
4101 emit_extra_methods (MonoAotCompile *acfg)
4103 int i, table_size, buf_size;
4106 guint32 *info_offsets;
4109 HashEntry *entry, *new_entry;
4112 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4114 buf_size = acfg->extra_methods->len * 256 + 256;
4115 p = buf = g_malloc (buf_size);
4117 /* Encode method info */
4119 /* So offsets are > 0 */
4122 for (i = 0; i < acfg->extra_methods->len; ++i) {
4123 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4124 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4130 info_offsets [i] = p - buf;
4132 if (method->wrapper_type) {
4135 // FIXME: Optimize disk usage
4136 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
4137 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4138 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
4141 name = mono_method_full_name (cfg->orig_method, TRUE);
4144 encode_value (1, p, &p);
4145 strcpy ((char*)p, name);
4146 p += strlen (name ) + 1;
4149 encode_value (0, p, &p);
4150 encode_method_ref (acfg, method, p, &p);
4153 g_assert ((p - buf) < buf_size);
4156 g_assert ((p - buf) < buf_size);
4158 /* Emit method info */
4159 sprintf (symbol, "extra_method_info");
4160 emit_section_change (acfg, ".text", 1);
4161 emit_global (acfg, symbol, FALSE);
4162 emit_alignment (acfg, 8);
4163 emit_label (acfg, symbol);
4165 emit_bytes (acfg, buf, p - buf);
4170 * Construct a chained hash table for mapping indexes in extra_method_info to
4173 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4174 table = g_ptr_array_sized_new (table_size);
4175 for (i = 0; i < table_size; ++i)
4176 g_ptr_array_add (table, NULL);
4177 for (i = 0; i < acfg->extra_methods->len; ++i) {
4178 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4179 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4185 key = info_offsets [i];
4186 value = get_method_index (acfg, method);
4188 if (method->wrapper_type) {
4189 hash = g_str_hash (method->name) % table_size;
4192 hash = 0 % table_size;
4195 /* FIXME: Allocate from the mempool */
4196 new_entry = g_new0 (HashEntry, 1);
4197 new_entry->key = key;
4198 new_entry->value = value;
4200 entry = g_ptr_array_index (table, hash);
4201 if (entry == NULL) {
4202 new_entry->index = hash;
4203 g_ptr_array_index (table, hash) = new_entry;
4206 entry = entry->next;
4208 entry->next = new_entry;
4209 new_entry->index = table->len;
4210 g_ptr_array_add (table, new_entry);
4214 /* Emit the table */
4215 sprintf (symbol, "extra_method_table");
4216 emit_section_change (acfg, ".text", 0);
4217 emit_global (acfg, symbol, FALSE);
4218 emit_alignment (acfg, 8);
4219 emit_label (acfg, symbol);
4221 g_assert (table_size < 65000);
4222 emit_int32 (acfg, table_size);
4223 g_assert (table->len < 65000);
4224 for (i = 0; i < table->len; ++i) {
4225 HashEntry *entry = g_ptr_array_index (table, i);
4227 if (entry == NULL) {
4228 emit_int32 (acfg, 0);
4229 emit_int32 (acfg, 0);
4230 emit_int32 (acfg, 0);
4232 g_assert (entry->key > 0);
4233 emit_int32 (acfg, entry->key);
4234 emit_int32 (acfg, entry->value);
4236 emit_int32 (acfg, entry->next->index);
4238 emit_int32 (acfg, 0);
4243 * Emit a table reverse mapping method indexes to their index in extra_method_info.
4244 * This is used by mono_aot_find_jit_info ().
4246 sprintf (symbol, "extra_method_info_offsets");
4247 emit_section_change (acfg, ".text", 0);
4248 emit_global (acfg, symbol, FALSE);
4249 emit_alignment (acfg, 8);
4250 emit_label (acfg, symbol);
4252 emit_int32 (acfg, acfg->extra_methods->len);
4253 for (i = 0; i < acfg->extra_methods->len; ++i) {
4254 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4256 emit_int32 (acfg, get_method_index (acfg, method));
4257 emit_int32 (acfg, info_offsets [i]);
4262 emit_method_order (MonoAotCompile *acfg)
4268 sprintf (symbol, "method_order");
4269 emit_section_change (acfg, ".text", 1);
4270 emit_global (acfg, symbol, FALSE);
4271 emit_alignment (acfg, 8);
4272 emit_label (acfg, symbol);
4274 /* First emit an index table */
4277 for (l = acfg->method_order; l != NULL; l = l->next) {
4278 i = GPOINTER_TO_UINT (l->data);
4280 if (acfg->cfgs [i]) {
4281 if ((index % 1024) == 0) {
4282 emit_int32 (acfg, i);
4290 emit_int32 (acfg, 0xffffff);
4292 /* Then emit the whole method order */
4293 for (l = acfg->method_order; l != NULL; l = l->next) {
4294 i = GPOINTER_TO_UINT (l->data);
4296 if (acfg->cfgs [i]) {
4297 emit_int32 (acfg, i);
4302 sprintf (symbol, "method_order_end");
4303 emit_section_change (acfg, ".text", 1);
4304 emit_global (acfg, symbol, FALSE);
4305 emit_label (acfg, symbol);
4309 emit_exception_info (MonoAotCompile *acfg)
4314 sprintf (symbol, "ex_info");
4315 emit_section_change (acfg, ".text", 1);
4316 emit_global (acfg, symbol, FALSE);
4317 emit_alignment (acfg, 8);
4318 emit_label (acfg, symbol);
4320 /* To reduce size of generated assembly */
4321 sprintf (symbol, "ex");
4322 emit_label (acfg, symbol);
4324 for (i = 0; i < acfg->nmethods; ++i) {
4326 emit_exception_debug_info (acfg, acfg->cfgs [i]);
4329 sprintf (symbol, "ex_info_offsets");
4330 emit_section_change (acfg, ".text", 1);
4331 emit_global (acfg, symbol, FALSE);
4332 emit_alignment (acfg, 8);
4333 emit_label (acfg, symbol);
4335 for (i = 0; i < acfg->nmethods; ++i) {
4336 if (acfg->cfgs [i]) {
4337 sprintf (symbol, ".Le_%x_p", i);
4338 emit_symbol_diff (acfg, symbol, "ex", 0);
4340 emit_int32 (acfg, 0);
4347 emit_class_info (MonoAotCompile *acfg)
4352 sprintf (symbol, "class_info");
4353 emit_section_change (acfg, ".text", 1);
4354 emit_global (acfg, symbol, FALSE);
4355 emit_alignment (acfg, 8);
4356 emit_label (acfg, symbol);
4358 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4359 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4361 sprintf (symbol, "class_info_offsets");
4362 emit_section_change (acfg, ".text", 1);
4363 emit_global (acfg, symbol, FALSE);
4364 emit_alignment (acfg, 8);
4365 emit_label (acfg, symbol);
4367 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4368 sprintf (symbol, ".LK_I_%x", i);
4369 emit_symbol_diff (acfg, symbol, "class_info", 0);
4374 typedef struct ClassNameTableEntry {
4375 guint32 token, index;
4376 struct ClassNameTableEntry *next;
4377 } ClassNameTableEntry;
4380 emit_class_name_table (MonoAotCompile *acfg)
4383 guint32 token, hash;
4388 ClassNameTableEntry *entry, *new_entry;
4391 * Construct a chained hash table for mapping class names to typedef tokens.
4393 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4394 table = g_ptr_array_sized_new (table_size);
4395 for (i = 0; i < table_size; ++i)
4396 g_ptr_array_add (table, NULL);
4397 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4398 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4399 klass = mono_class_get (acfg->image, token);
4400 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4401 hash = g_str_hash (full_name) % table_size;
4404 /* FIXME: Allocate from the mempool */
4405 new_entry = g_new0 (ClassNameTableEntry, 1);
4406 new_entry->token = token;
4408 entry = g_ptr_array_index (table, hash);
4409 if (entry == NULL) {
4410 new_entry->index = hash;
4411 g_ptr_array_index (table, hash) = new_entry;
4414 entry = entry->next;
4416 entry->next = new_entry;
4417 new_entry->index = table->len;
4418 g_ptr_array_add (table, new_entry);
4422 /* Emit the table */
4423 sprintf (symbol, "class_name_table");
4424 emit_section_change (acfg, ".text", 0);
4425 emit_global (acfg, symbol, FALSE);
4426 emit_alignment (acfg, 8);
4427 emit_label (acfg, symbol);
4429 /* FIXME: Optimize memory usage */
4430 g_assert (table_size < 65000);
4431 emit_int16 (acfg, table_size);
4432 g_assert (table->len < 65000);
4433 for (i = 0; i < table->len; ++i) {
4434 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4436 if (entry == NULL) {
4437 emit_int16 (acfg, 0);
4438 emit_int16 (acfg, 0);
4440 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4442 emit_int16 (acfg, entry->next->index);
4444 emit_int16 (acfg, 0);
4450 emit_image_table (MonoAotCompile *acfg)
4456 * The image table is small but referenced in a lot of places.
4457 * So we emit it at once, and reference its elements by an index.
4460 sprintf (symbol, "mono_image_table");
4461 emit_section_change (acfg, ".text", 1);
4462 emit_global (acfg, symbol, FALSE);
4463 emit_alignment (acfg, 8);
4464 emit_label (acfg, symbol);
4466 emit_int32 (acfg, acfg->image_table->len);
4467 for (i = 0; i < acfg->image_table->len; i++) {
4468 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4469 MonoAssemblyName *aname = &image->assembly->aname;
4471 /* FIXME: Support multi-module assemblies */
4472 g_assert (image->assembly->image == image);
4474 emit_string (acfg, image->assembly_name);
4475 emit_string (acfg, image->guid);
4476 emit_string (acfg, aname->culture ? aname->culture : "");
4477 emit_string (acfg, (const char*)aname->public_key_token);
4479 emit_alignment (acfg, 8);
4480 emit_int32 (acfg, aname->flags);
4481 emit_int32 (acfg, aname->major);
4482 emit_int32 (acfg, aname->minor);
4483 emit_int32 (acfg, aname->build);
4484 emit_int32 (acfg, aname->revision);
4489 emit_got_info (MonoAotCompile *acfg)
4494 guint32 *got_info_offsets;
4498 * - optimize offsets table.
4499 * - reduce number of exported symbols.
4500 * - emit info for a klass only once.
4501 * - determine when a method uses a GOT slot which is guaranteed to be already
4503 * - clean up and document the code.
4504 * - use String.Empty in class libs.
4507 /* Encode info required to decode shared GOT entries */
4508 buf_size = acfg->shared_patches->len * 64;
4509 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4510 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
4511 for (i = 0; i < acfg->shared_patches->len; ++i) {
4512 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
4514 /* No need to encode the patch type */
4515 got_info_offsets [i] = p - buf;
4516 encode_patch (acfg, ji, p, &p);
4519 g_assert (p - buf <= buf_size);
4521 acfg->stats.got_info_size = p - buf;
4523 /* Emit got_info table */
4524 sprintf (symbol, "got_info");
4525 emit_section_change (acfg, ".text", 1);
4526 emit_global (acfg, symbol, FALSE);
4527 emit_alignment (acfg, 8);
4528 emit_label (acfg, symbol);
4530 emit_bytes (acfg, buf, p - buf);
4532 /* Emit got_info_offsets table */
4533 sprintf (symbol, "got_info_offsets");
4534 emit_section_change (acfg, ".text", 1);
4535 emit_global (acfg, symbol, FALSE);
4536 emit_alignment (acfg, 8);
4537 emit_label (acfg, symbol);
4539 for (i = 0; i < acfg->shared_patches->len; ++i)
4540 emit_int32 (acfg, got_info_offsets [i]);
4542 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
4546 emit_got (MonoAotCompile *acfg)
4550 /* Don't make GOT global so accesses to it don't need relocations */
4551 sprintf (symbol, "got");
4552 emit_section_change (acfg, ".bss", 1);
4553 emit_alignment (acfg, 8);
4554 emit_label (acfg, symbol);
4555 if ((acfg->got_offset + acfg->num_trampoline_got_entries) > 0)
4556 emit_zero_bytes (acfg, (int)((acfg->got_offset + acfg->num_trampoline_got_entries) * sizeof (gpointer)));
4558 sprintf (symbol, "got_addr");
4559 emit_section_change (acfg, ".data", 1);
4560 emit_global (acfg, symbol, FALSE);
4561 emit_alignment (acfg, 8);
4562 emit_label (acfg, symbol);
4563 emit_pointer (acfg, "got");
4565 sprintf (symbol, "got_size");
4566 emit_section_change (acfg, ".data", 1);
4567 emit_global (acfg, symbol, FALSE);
4568 emit_alignment (acfg, 8);
4569 emit_label (acfg, symbol);
4570 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4574 emit_globals (MonoAotCompile *acfg)
4578 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4580 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4582 opts_str = g_strdup_printf ("%d", acfg->opts);
4583 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4586 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4588 if (acfg->aot_opts.bind_to_runtime_version)
4589 emit_string_symbol (acfg, "mono_runtime_version", FULL_VERSION);
4591 emit_string_symbol (acfg, "mono_runtime_version", "");
4594 * Some platforms like the iphone have no working dlsym (). To work around this,
4595 * we create an ELF ctor function which will be invoked by dlopen, and which
4596 * will call a function in the AOT loader to register the symbols used by the
4598 * When static linking, we emit a global which will point to the symbol table.
4600 if (acfg->aot_opts.no_dlsym) {
4604 if (acfg->aot_opts.static_link)
4605 /* Emit a string holding the assembly name */
4606 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4608 /* Emit the names */
4609 for (i = 0; i < acfg->globals->len; ++i) {
4610 char *name = g_ptr_array_index (acfg->globals, i);
4612 sprintf (symbol, "name_%d", i);
4613 emit_section_change (acfg, ".text", 1);
4614 emit_label (acfg, symbol);
4615 emit_string (acfg, name);
4618 /* Emit the globals table */
4619 sprintf (symbol, "globals");
4620 emit_section_change (acfg, ".data", 0);
4621 /* This is not a global, since it is accessed by the init function */
4622 emit_alignment (acfg, 8);
4623 emit_label (acfg, symbol);
4625 for (i = 0; i < acfg->globals->len; ++i) {
4626 char *name = g_ptr_array_index (acfg->globals, i);
4628 sprintf (symbol, "name_%d", i);
4629 emit_pointer (acfg, symbol);
4631 sprintf (symbol, "%s", name);
4632 emit_pointer (acfg, symbol);
4634 /* Null terminate the table */
4635 emit_pointer (acfg, NULL);
4636 emit_pointer (acfg, NULL);
4638 if (acfg->aot_opts.static_link) {
4642 * Emit a global symbol which can be passed by an embedding app to
4643 * mono_aot_register_module ().
4645 #if defined(__MACH__)
4646 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4648 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4651 /* Get rid of characters which cannot occur in symbols */
4653 for (p = symbol; *p; ++p) {
4654 if (!(isalnum (*p) || *p == '_'))
4657 acfg->static_linking_symbol = g_strdup (symbol);
4658 emit_global_inner (acfg, symbol, FALSE);
4659 emit_alignment (acfg, 8);
4660 emit_label (acfg, symbol);
4661 emit_pointer (acfg, "globals");
4663 sprintf (symbol, "init_%s", acfg->image->assembly->aname.name);
4664 emit_section_change (acfg, ".text", 1);
4665 emit_alignment (acfg, 8);
4666 emit_label (acfg, symbol);
4667 #ifdef USE_BIN_WRITER
4668 g_assert_not_reached ();
4671 fprintf (acfg->fp, "leaq globals(%%rip), %%rdi\n");
4672 fprintf (acfg->fp, "call mono_aot_register_globals@PLT\n");
4673 fprintf (acfg->fp, "ret\n");
4674 fprintf (acfg->fp, ".section .ctors,\"aw\",@progbits\n");
4675 emit_alignment (acfg, 8);
4676 emit_pointer (acfg, symbol);
4677 #elif defined(__arm__) && defined(__MACH__)
4679 fprintf (acfg->fp, ".text\n");
4680 fprintf (acfg->fp, ".align 3\n");
4682 fprintf (acfg->fp, "ldr r0, .L5\n");
4683 fprintf (acfg->fp, ".LPIC0:\n");
4684 fprintf (acfg->fp, "add r0, pc, r0\n");
4685 fprintf (acfg->fp, "ldr r0, [r0]\n");
4686 fprintf (acfg->fp, "b _mono_aot_register_globals@PLT\n");
4687 fprintf (acfg->fp, ".align 2\n");
4689 fprintf (acfg->fp, ".L5:\n");
4690 fprintf (acfg->fp, ".long globals_ptr-(.LPIC0+8)\n");
4692 fprintf (acfg->fp, ".data\n");
4693 fprintf (acfg->fp, ".align 2\n");
4694 fprintf (acfg->fp, "globals_ptr:\n");
4695 fprintf (acfg->fp, ".long globals\n");
4697 fprintf (acfg->fp, ".mod_init_func\n");
4698 fprintf (acfg->fp, ".align 2\n");
4699 fprintf (acfg->fp, ".long %s@target1\n", symbol);
4701 #elif defined(__arm__)
4703 * Taken from gcc generated code for:
4705 * void foo () { bar (&i); }
4706 * gcc --shared -fPIC -O2
4708 fprintf (acfg->fp, "ldr r3, .L5\n");
4709 fprintf (acfg->fp, "ldr r0, .L5+4\n");
4710 fprintf (acfg->fp, ".LPIC0:\n");
4711 fprintf (acfg->fp, "add r3, pc, r3\n");
4712 fprintf (acfg->fp, "add r0, r3, r0\n");
4713 fprintf (acfg->fp, "b mono_aot_register_globals(PLT)\n");
4715 fprintf (acfg->fp, ".L5:\n");
4716 fprintf (acfg->fp, ".word _GLOBAL_OFFSET_TABLE_-(.LPIC0+8)\n");
4717 fprintf (acfg->fp, ".word globals(GOTOFF)\n");
4719 fprintf (acfg->fp, ".section .init_array,\"aw\",%%init_array\n");
4720 fprintf (acfg->fp, ".align 2\n");
4721 fprintf (acfg->fp, ".word %s(target1)\n", symbol);
4723 g_assert_not_reached ();
4731 acfg_free (MonoAotCompile *acfg)
4735 for (i = 0; i < acfg->nmethods; ++i)
4737 g_free (acfg->cfgs [i]);
4738 g_free (acfg->cfgs);
4739 g_free (acfg->static_linking_symbol);
4740 g_ptr_array_free (acfg->methods, TRUE);
4741 g_ptr_array_free (acfg->shared_patches, TRUE);
4742 g_ptr_array_free (acfg->image_table, TRUE);
4743 g_ptr_array_free (acfg->globals, TRUE);
4744 g_hash_table_destroy (acfg->method_indexes);
4745 g_hash_table_destroy (acfg->plt_offset_to_patch);
4746 g_hash_table_destroy (acfg->patch_to_plt_offset);
4747 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
4748 g_hash_table_destroy (acfg->method_to_cfg);
4749 g_hash_table_destroy (acfg->token_info_hash);
4750 g_hash_table_destroy (acfg->image_hash);
4751 mono_mempool_destroy (acfg->mempool);
4756 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4758 MonoImage *image = ass->image;
4760 int i, res, methods_len;
4761 MonoAotCompile *acfg;
4765 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4767 acfg = g_new0 (MonoAotCompile, 1);
4768 acfg->methods = g_ptr_array_new ();
4769 acfg->method_indexes = g_hash_table_new (NULL, NULL);
4770 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4771 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4772 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4773 acfg->shared_patches = g_ptr_array_new ();
4774 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4775 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4776 acfg->image_hash = g_hash_table_new (NULL, NULL);
4777 acfg->image_table = g_ptr_array_new ();
4778 acfg->globals = g_ptr_array_new ();
4779 acfg->image = image;
4781 acfg->mempool = mono_mempool_new ();
4782 acfg->extra_methods = g_ptr_array_new ();
4783 InitializeCriticalSection (&acfg->mutex);
4785 mono_aot_parse_options (aot_options, &acfg->aot_opts);
4787 load_profile_files (acfg);
4791 acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 10240 : 0;
4793 acfg->method_index = 1;
4795 /* Collect methods */
4796 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4798 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4800 method = mono_get_method (acfg->image, token, NULL);
4802 /* Load all methods eagerly to skip the slower lazy loading code */
4803 mono_class_setup_methods (method->klass);
4805 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4806 /* Compile the wrapper instead */
4807 /* We do this here instead of add_wrappers () because it is easy to do it here */
4808 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4812 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4813 add_method_with_index (acfg, method, i);
4814 acfg->method_index ++;
4817 add_generic_instances (acfg);
4819 if (acfg->aot_opts.full_aot)
4820 add_wrappers (acfg);
4822 acfg->cfgs_size = acfg->methods->len + 32;
4823 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
4825 /* PLT offset 0 is reserved for the PLT trampoline */
4826 acfg->plt_offset = 1;
4828 /* Compile methods */
4831 if (acfg->aot_opts.nthreads > 0) {
4836 gpointer *user_data;
4837 MonoMethod **methods;
4839 methods_len = acfg->methods->len;
4841 len = acfg->methods->len / acfg->aot_opts.nthreads;
4844 * Partition the list of methods into fragments, and hand it to threads to
4847 threads = g_ptr_array_new ();
4848 /* Make a copy since acfg->methods is modified by compile_method () */
4849 methods = g_new0 (MonoMethod*, methods_len);
4850 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
4851 for (i = 0; i < methods_len; ++i)
4852 methods [i] = g_ptr_array_index (acfg->methods, i);
4854 while (i < methods_len) {
4855 frag = g_ptr_array_new ();
4856 for (j = 0; j < len; ++j) {
4857 if (i < methods_len) {
4858 g_ptr_array_add (frag, methods [i]);
4863 user_data = g_new0 (gpointer, 3);
4864 user_data [0] = mono_domain_get ();
4865 user_data [1] = acfg;
4866 user_data [2] = frag;
4868 handle = CreateThread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
4869 g_ptr_array_add (threads, handle);
4873 for (i = 0; i < threads->len; ++i) {
4874 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
4880 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
4881 for (i = methods_len; i < acfg->methods->len; ++i) {
4882 /* This can new methods to acfg->methods */
4883 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4888 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
4892 alloc_got_slots (acfg);
4898 emit_extra_methods (acfg);
4900 emit_method_order (acfg);
4902 emit_trampolines (acfg);
4904 emit_class_name_table (acfg);
4906 emit_got_info (acfg);
4908 emit_exception_info (acfg);
4910 emit_class_info (acfg);
4914 emit_image_table (acfg);
4918 emit_globals (acfg);
4920 sprintf (symbol, "mem_end");
4921 emit_section_change (acfg, ".text", 1);
4922 emit_global (acfg, symbol, FALSE);
4923 emit_alignment (acfg, 8);
4924 emit_label (acfg, symbol);
4928 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
4930 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)));
4933 res = emit_writeout (acfg);
4939 acfg->stats.link_time = TV_ELAPSED (atv, btv);
4941 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);
4942 if (acfg->stats.genericcount)
4943 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4944 if (acfg->stats.abscount)
4945 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4946 if (acfg->stats.wrappercount)
4947 printf ("%d methods contain wrapper references (%d%%)\n", acfg->stats.wrappercount, acfg->stats.mcount ? (acfg->stats.wrappercount * 100) / acfg->stats.mcount : 100);
4948 if (acfg->stats.lmfcount)
4949 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4950 if (acfg->stats.ocount)
4951 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4952 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);
4953 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4954 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);
4956 printf ("GOT slot distribution:\n");
4957 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4958 if (acfg->stats.got_slot_types [i])
4959 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4971 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)