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
44 #include <limits.h> /* for PAGESIZE */
49 #include <mono/metadata/tabledefs.h>
50 #include <mono/metadata/class.h>
51 #include <mono/metadata/object.h>
52 #include <mono/metadata/tokentype.h>
53 #include <mono/metadata/appdomain.h>
54 #include <mono/metadata/debug-helpers.h>
55 #include <mono/metadata/assembly.h>
56 #include <mono/metadata/metadata-internals.h>
57 #include <mono/metadata/marshal.h>
58 #include <mono/metadata/gc-internal.h>
59 #include <mono/metadata/method-builder.h>
60 #include <mono/metadata/monitor.h>
61 #include <mono/utils/mono-logger.h>
62 #include <mono/utils/mono-compiler.h>
63 #include <mono/utils/mono-time.h>
65 #ifndef PLATFORM_WIN32
66 #include <mono/utils/freebsd-elf32.h>
67 #include <mono/utils/freebsd-elf64.h>
75 #define TV_DECLARE(name) gint64 name
76 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
77 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
80 #define SHARED_EXT ".dll"
81 #elif defined(__ppc__) && defined(__MACH__)
82 #define SHARED_EXT ".dylib"
84 #define SHARED_EXT ".so"
87 #if defined(sparc) || defined(__ppc__) || defined(__powerpc__) || defined(__MACH__)
88 #define AS_STRING_DIRECTIVE ".asciz"
91 #define AS_STRING_DIRECTIVE ".string"
96 // .byte generates 1 byte per expression.
97 // .short generates 2 bytes per expression.
98 // .long generates 4 bytes per expression.
99 // .quad generates 8 bytes per expression.
101 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
102 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
104 typedef struct MonoAotOptions {
107 gboolean write_symbols;
108 gboolean metadata_only;
109 gboolean bind_to_runtime_version;
112 gboolean static_link;
117 typedef struct MonoAotStats {
118 int ccount, mcount, lmfcount, abscount, wrappercount, gcount, ocount, genericcount;
119 int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
120 int methods_without_got_slots, direct_calls, all_calls;
122 int got_slot_types [MONO_PATCH_INFO_NONE];
123 int jit_time, gen_time, link_time;
126 #if defined(__x86_64__) && !defined(PLATFORM_WIN32)
127 #define USE_ELF_WRITER 1
128 #define USE_ELF_RELA 1
131 #if defined(__i386__) && !defined(PLATFORM_WIN32)
132 #define USE_ELF_WRITER 1
135 #if defined(__arm__) && !defined(__MACH__)
136 #define USE_ELF_WRITER 1
139 #if defined(USE_ELF_WRITER)
140 #define USE_BIN_WRITER 1
143 #ifdef USE_BIN_WRITER
145 typedef struct _BinSymbol BinSymbol;
146 typedef struct _BinReloc BinReloc;
147 typedef struct _BinSection BinSection;
161 typedef struct MonoAotCompile {
164 GHashTable *method_indexes;
167 GHashTable *patch_to_plt_offset;
168 GHashTable *plt_offset_to_patch;
169 GHashTable *patch_to_shared_got_offset;
170 GPtrArray *shared_patches;
171 GHashTable *image_hash;
172 GHashTable *method_to_cfg;
173 GHashTable *token_info_hash;
174 GPtrArray *extra_methods;
175 GPtrArray *image_table;
178 /* Number of trampolines emitted into the AOT file */
179 guint32 num_aot_trampolines;
180 guint32 got_offset, plt_offset;
181 /* Number of GOT entries reserved for trampolines */
182 guint32 num_trampoline_got_entries;
183 MonoAotOptions aot_opts;
186 MonoMemPool *mempool;
189 char *static_linking_symbol;
190 CRITICAL_SECTION mutex;
191 #ifdef USE_BIN_WRITER
193 BinSection *sections;
194 BinSection *cur_section;
195 BinReloc *relocations;
201 int mode; /* emit mode */
202 int col_count; /* bytes emitted per .byte line */
206 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
207 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
209 #ifdef HAVE_ARRAY_ELEM_INIT
210 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
211 #define MSGSTRFIELD1(line) str##line
212 static const struct msgstr_t {
213 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
214 #include "patch-info.h"
217 #define PATCH_INFO(a,b) b,
218 #include "patch-info.h"
221 static const gint16 opidx [] = {
222 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
223 #include "patch-info.h"
228 get_patch_name (int info)
230 return (const char*)&opstr + opidx [info];
234 #define PATCH_INFO(a,b) b,
235 static const char* const
236 patch_types [MONO_PATCH_INFO_NUM + 1] = {
237 #include "patch-info.h"
242 get_patch_name (int info)
244 return patch_types [info];
250 emit_global (MonoAotCompile *acfg, const char *name, gboolean func);
253 is_got_patch (MonoJumpInfoType patch_type)
258 static G_GNUC_UNUSED int
259 ilog2(register int value)
262 while (value & ~0xf) count += 4, value >>= 4;
263 while (value) count++, value >>= 1;
267 #ifdef USE_BIN_WRITER
269 typedef struct _BinLabel BinLabel;
280 BinSection *val2_section;
293 gboolean is_function;
311 emit_start (MonoAotCompile *acfg)
313 acfg->labels = g_hash_table_new (g_str_hash, g_str_equal);
317 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
321 if (acfg->cur_section && acfg->cur_section->subsection == subsection_index
322 && strcmp (acfg->cur_section->name, section_name) == 0)
324 for (section = acfg->sections; section; section = section->next) {
325 if (section->subsection == subsection_index && strcmp (section->name, section_name) == 0) {
326 acfg->cur_section = section;
331 section = g_new0 (BinSection, 1);
332 section->name = g_strdup (section_name);
333 section->subsection = subsection_index;
334 section->next = acfg->sections;
335 acfg->sections = section;
336 acfg->cur_section = section;
341 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
343 BinSymbol *symbol = g_new0 (BinSymbol, 1);
344 symbol->name = g_strdup (name);
345 symbol->is_function = func;
346 symbol->is_global = TRUE;
347 symbol->section = acfg->cur_section;
348 /* FIXME: we align after this call... */
349 symbol->offset = symbol->section->cur_offset;
350 symbol->next = acfg->symbols;
351 acfg->symbols = symbol;
355 emit_label (MonoAotCompile *acfg, const char *name)
357 BinLabel *label = g_new0 (BinLabel, 1);
358 label->name = g_strdup (name);
359 label->section = acfg->cur_section;
360 label->offset = acfg->cur_section->cur_offset;
361 g_hash_table_insert (acfg->labels, label->name, label);
365 emit_ensure_buffer (BinSection *section, int size)
367 int new_offset = section->cur_offset + size;
368 if (new_offset >= section->data_len) {
369 int new_size = section->data_len? section->data_len * 2: 256;
371 while (new_size <= new_offset)
373 data = g_malloc0 (new_size);
374 memcpy (data, section->data, section->data_len);
375 g_free (section->data);
376 section->data = data;
377 section->data_len = new_size;
382 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
384 emit_ensure_buffer (acfg->cur_section, size);
385 memcpy (acfg->cur_section->data + acfg->cur_section->cur_offset, buf, size);
386 acfg->cur_section->cur_offset += size;
390 emit_string (MonoAotCompile *acfg, const char *value)
392 int size = strlen (value) + 1;
393 emit_bytes (acfg, (const guint8*)value, size);
397 emit_line (MonoAotCompile *acfg)
399 /* Nothing to do in binary writer */
403 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
405 emit_section_change (acfg, ".text", 1);
406 emit_global (acfg, name, FALSE);
407 emit_label (acfg, name);
408 emit_string (acfg, value);
412 emit_alignment (MonoAotCompile *acfg, int size)
414 int offset = acfg->cur_section->cur_offset;
416 offset += (size - 1);
417 offset &= ~(size - 1);
418 add = offset - acfg->cur_section->cur_offset;
420 emit_ensure_buffer (acfg->cur_section, add);
421 acfg->cur_section->cur_offset += add;
426 emit_pointer (MonoAotCompile *acfg, const char *target)
432 g_assert_not_reached ();
433 emit_alignment (acfg, sizeof (gpointer));
434 reloc = g_new0 (BinReloc, 1);
435 reloc->val1 = g_strdup (target);
436 reloc->section = acfg->cur_section;
437 reloc->section_offset = acfg->cur_section->cur_offset;
438 reloc->next = acfg->relocations;
439 acfg->relocations = reloc;
440 if (strcmp (reloc->section->name, ".data") == 0) {
442 g_print ("reloc: %s at %d\n", target, acfg->cur_section->cur_offset);
444 acfg->cur_section->cur_offset += sizeof (gpointer);
448 emit_int16 (MonoAotCompile *acfg, int value)
451 emit_ensure_buffer (acfg->cur_section, 2);
452 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
453 acfg->cur_section->cur_offset += 2;
454 /* FIXME: little endian */
456 data [1] = value >> 8;
460 emit_int32 (MonoAotCompile *acfg, int value)
463 emit_ensure_buffer (acfg->cur_section, 4);
464 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
465 acfg->cur_section->cur_offset += 4;
466 /* FIXME: little endian */
468 data [1] = value >> 8;
469 data [2] = value >> 16;
470 data [3] = value >> 24;
474 create_reloc (MonoAotCompile *acfg, const char *end, const char* start, int offset)
477 reloc = mono_mempool_alloc0 (acfg->mempool, sizeof (BinReloc));
478 reloc->val1 = mono_mempool_strdup (acfg->mempool, end);
479 if (strcmp (start, ".") == 0) {
480 reloc->val2_section = acfg->cur_section;
481 reloc->val2_offset = acfg->cur_section->cur_offset;
483 reloc->val2 = mono_mempool_strdup (acfg->mempool, start);
485 reloc->offset = offset;
486 reloc->section = acfg->cur_section;
487 reloc->section_offset = acfg->cur_section->cur_offset;
488 reloc->next = acfg->relocations;
489 acfg->relocations = reloc;
494 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
496 create_reloc (acfg, end, start, offset);
497 acfg->cur_section->cur_offset += 4;
498 /*if (strcmp (reloc->section->name, ".data") == 0) {
500 g_print ("reloc: %s - %s + %d at %d\n", end, start, offset, acfg->cur_section->cur_offset - 4);
505 * Emit a relocation entry of type RELOC_TYPE against symbol SYMBOL at the current PC.
508 static G_GNUC_UNUSED void
509 emit_reloc (MonoAotCompile *acfg, int reloc_type, const char *symbol, int addend)
511 BinReloc *reloc = create_reloc (acfg, symbol, ".", addend);
512 reloc->reloc_type = reloc_type;
516 emit_zero_bytes (MonoAotCompile *acfg, int num)
518 emit_ensure_buffer (acfg->cur_section, num);
519 acfg->cur_section->cur_offset += num;
522 #ifdef USE_ELF_WRITER
542 /* Relocation types */
543 #define R_ARM_CALL 28
544 #define R_ARM_ALU_PC_G0_NC 59
546 #if SIZEOF_VOID_P == 4
548 typedef Elf32_Ehdr ElfHeader;
549 typedef Elf32_Shdr ElfSectHeader;
550 typedef Elf32_Phdr ElfProgHeader;
551 typedef Elf32_Sym ElfSymbol;
552 typedef Elf32_Rel ElfReloc;
553 typedef Elf32_Rela ElfRelocA;
554 typedef Elf32_Dyn ElfDynamic;
558 typedef Elf64_Ehdr ElfHeader;
559 typedef Elf64_Shdr ElfSectHeader;
560 typedef Elf64_Phdr ElfProgHeader;
561 typedef Elf64_Sym ElfSymbol;
562 typedef Elf64_Rel ElfReloc;
563 typedef Elf64_Rela ElfRelocA;
564 typedef Elf64_Dyn ElfDynamic;
576 static SectInfo section_info [] = {
578 {".hash", SHT_HASH, 4, 2, SIZEOF_VOID_P},
579 {".dynsym", SHT_DYNSYM, sizeof (ElfSymbol), 2, SIZEOF_VOID_P},
580 {".dynstr", SHT_STRTAB, 0, 2, 1},
581 {".rel.dyn", SHT_REL, sizeof (ElfReloc), 2, SIZEOF_VOID_P},
582 {".rela.dyn", SHT_RELA, sizeof (ElfRelocA), 2, SIZEOF_VOID_P},
583 {".text", SHT_PROGBITS, 0, 6, 4096},
584 {".dynamic", SHT_DYNAMIC, sizeof (ElfDynamic), 3, SIZEOF_VOID_P},
585 {".got.plt", SHT_PROGBITS, SIZEOF_VOID_P, 3, SIZEOF_VOID_P},
586 {".data", SHT_PROGBITS, 0, 3, 8},
587 {".bss", SHT_NOBITS, 0, 3, 8},
588 {".shstrtab", SHT_STRTAB, 0, 0, 1},
589 {".symtab", SHT_SYMTAB, sizeof (ElfSymbol), 0, SIZEOF_VOID_P},
590 {".strtab", SHT_STRTAB, 0, 0, 1}
599 str_table_add (ElfStrTable *table, const char* value)
603 table->data = g_string_new_len ("", 1);
604 table->hash = g_hash_table_new (g_str_hash, g_str_equal);
606 idx = GPOINTER_TO_UINT (g_hash_table_lookup (table->hash, value));
609 idx = table->data->len;
610 g_string_append (table->data, value);
611 g_string_append_c (table->data, 0);
612 g_hash_table_insert (table->hash, (void*)value, GUINT_TO_POINTER (idx));
617 append_subsection (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection *sect, BinSection *add)
619 int offset = sect->cur_offset;
620 /*offset += (sheaders [sect->shidx].sh_addralign - 1);
621 offset &= ~(sheaders [sect->shidx].sh_addralign - 1);*/
624 emit_ensure_buffer (sect, offset);
625 g_print ("section %s aligned to %d from %d\n", sect->name, offset, sect->cur_offset);
626 sect->cur_offset = offset;
628 emit_ensure_buffer (sect, add->cur_offset);
629 memcpy (sect->data + sect->cur_offset, add->data, add->cur_offset);
631 sect->cur_offset += add->cur_offset;
632 add->cur_offset = offset; /* it becomes the offset in the parent section */
633 g_print ("subsection %d of %s added at offset %d (align: %d)\n", add->subsection, sect->name, add->cur_offset, (int)sheaders [sect->shidx].sh_addralign);
638 /* merge the subsections */
640 collect_sections (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection **out, int num)
642 int i, j, maxs, num_sections;
647 for (sect = acfg->sections; sect; sect = sect->next) {
648 if (sect->subsection == 0) {
649 out [num_sections++] = sect;
650 g_assert (num_sections < num);
651 if (strcmp (sect->name, ".text") == 0) {
652 sect->shidx = SECT_TEXT;
653 } else if (strcmp (sect->name, ".data") == 0) {
654 sect->shidx = SECT_DATA;
655 } else if (strcmp (sect->name, ".bss") == 0) {
656 sect->shidx = SECT_BSS;
659 maxs = MAX (maxs, sect->subsection);
661 for (i = 0; i < num_sections; i++) {
662 for (j = 1; j <= maxs; ++j) {
663 for (sect = acfg->sections; sect; sect = sect->next) {
664 if (sect->subsection == j && strcmp (out [i]->name, sect->name) == 0) {
665 append_subsection (acfg, sheaders, out [i], sect);
674 elf_hash (const unsigned char *name)
676 unsigned long h = 0, g;
678 h = (h << 4) + *name++;
679 if ((g = h & 0xf0000000))
686 #define NUM_BUCKETS 17
689 build_hash (MonoAotCompile *acfg, int num_sections, ElfStrTable *dynstr)
692 int num_symbols = 1 + num_sections + 3;
695 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
696 if (!symbol->is_global)
699 str_table_add (dynstr, symbol->name);
700 /*g_print ("adding sym: %s\n", symbol->name);*/
702 str_table_add (dynstr, "__bss_start");
703 str_table_add (dynstr, "_edata");
704 str_table_add (dynstr, "_end");
706 data = g_new0 (int, num_symbols + 2 + NUM_BUCKETS);
707 data [0] = NUM_BUCKETS;
708 data [1] = num_symbols;
714 get_label_addr (MonoAotCompile *acfg, const char *name)
721 lab = g_hash_table_lookup (acfg->labels, name);
722 section = lab->section;
723 offset = lab->offset;
724 if (section->parent) {
725 value = section->parent->virt_offset + section->cur_offset + offset;
727 value = section->virt_offset + offset;
733 collect_syms (MonoAotCompile *acfg, int *hash, ElfStrTable *strtab, ElfSectHeader *sheaders, int *num_syms)
744 symbols = g_new0 (ElfSymbol, hash [1]);
746 symbols = g_new0 (ElfSymbol, *num_syms + SECT_NUM + 10); /* FIXME */
748 /* the first symbol is undef, all zeroes */
752 for (j = 1; j < SECT_NUM; ++j) {
753 symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
754 symbols [i].st_shndx = j;
755 symbols [i].st_value = sheaders [j].sh_addr;
759 for (section = acfg->sections; section; section = section->next) {
762 symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
763 if (strcmp (section->name, ".text") == 0) {
764 symbols [i].st_shndx = SECT_TEXT;
765 section->shidx = SECT_TEXT;
766 section->file_offset = 4096;
767 symbols [i].st_value = section->virt_offset;
768 } else if (strcmp (section->name, ".data") == 0) {
769 symbols [i].st_shndx = SECT_DATA;
770 section->shidx = SECT_DATA;
771 section->file_offset = 4096 + 28; /* FIXME */
772 symbols [i].st_value = section->virt_offset;
773 } else if (strcmp (section->name, ".bss") == 0) {
774 symbols [i].st_shndx = SECT_BSS;
775 section->shidx = SECT_BSS;
776 section->file_offset = 4096 + 28 + 8; /* FIXME */
777 symbols [i].st_value = section->virt_offset;
782 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
785 if (!symbol->is_global)
787 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, symbol->is_function? STT_FUNC : STT_OBJECT);
788 symbols [i].st_name = str_table_add (strtab, symbol->name);
789 /*g_print ("sym name %s tabled to %d\n", symbol->name, symbols [i].st_name);*/
790 section = symbol->section;
791 symbols [i].st_shndx = section->parent? section->parent->shidx: section->shidx;
792 lab = g_hash_table_lookup (acfg->labels, symbol->name);
793 offset = lab->offset;
794 if (section->parent) {
795 symbols [i].st_value = section->parent->virt_offset + section->cur_offset + offset;
797 symbols [i].st_value = section->virt_offset + offset;
801 /* add special symbols */
802 symbols [i].st_name = str_table_add (strtab, "__bss_start");
803 symbols [i].st_shndx = 0xfff1;
804 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
806 symbols [i].st_name = str_table_add (strtab, "_edata");
807 symbols [i].st_shndx = 0xfff1;
808 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
810 symbols [i].st_name = str_table_add (strtab, "_end");
811 symbols [i].st_shndx = 0xfff1;
812 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
818 /* add to hash table */
821 chain = hash + 2 + hash [0];
822 for (i = 0; i < hash [1]; ++i) {
824 /*g_print ("checking %d '%s' (sym %d)\n", symbols [i].st_name, strtab->data->str + symbols [i].st_name, i);*/
825 if (!symbols [i].st_name)
827 hashc = elf_hash ((guint8*)strtab->data->str + symbols [i].st_name);
828 slot = hashc % hash [0];
829 /*g_print ("hashing '%s' at slot %d (sym %d)\n", strtab->data->str + symbols [i].st_name, slot, i);*/
831 chain [i] = bucket [slot];
842 reloc_symbols (MonoAotCompile *acfg, ElfSymbol *symbols, ElfSectHeader *sheaders, ElfStrTable *strtab, gboolean dynamic)
850 for (section = acfg->sections; section; section = section->next) {
853 symbols [i].st_value = sheaders [section->shidx].sh_addr;
857 for (i = 1; i < SECT_NUM; ++i) {
858 symbols [i].st_value = sheaders [i].sh_addr;
861 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
864 if (dynamic && !symbol->is_global)
866 section = symbol->section;
867 lab = g_hash_table_lookup (acfg->labels, symbol->name);
868 offset = lab->offset;
869 if (section->parent) {
870 symbols [i].st_value = sheaders [section->parent->shidx].sh_addr + section->cur_offset + offset;
872 symbols [i].st_value = sheaders [section->shidx].sh_addr + offset;
877 symbols [i].st_value = sheaders [SECT_BSS].sh_addr;
880 symbols [i].st_value = sheaders [SECT_DATA].sh_addr + sheaders [SECT_DATA].sh_size;
883 symbols [i].st_value = sheaders [SECT_BSS].sh_addr + sheaders [SECT_BSS].sh_size;
888 resolve_reloc (MonoAotCompile *acfg, BinReloc *reloc, guint8 **out_data, gsize *out_vaddr, gsize *out_start_val, gsize *out_end_val)
891 gssize end_val, start_val;
894 end_val = get_label_addr (acfg, reloc->val1);
896 start_val = get_label_addr (acfg, reloc->val2);
897 } else if (reloc->val2_section) {
898 start_val = reloc->val2_offset;
899 if (reloc->val2_section->parent)
900 start_val += reloc->val2_section->parent->virt_offset + reloc->val2_section->cur_offset;
902 start_val += reloc->val2_section->virt_offset;
906 end_val = end_val - start_val + reloc->offset;
907 if (reloc->section->parent) {
908 data = reloc->section->parent->data;
909 data += reloc->section->cur_offset;
910 data += reloc->section_offset;
911 vaddr = reloc->section->parent->virt_offset;
912 vaddr += reloc->section->cur_offset;
913 vaddr += reloc->section_offset;
915 data = reloc->section->data;
916 data += reloc->section_offset;
917 vaddr = reloc->section->virt_offset;
918 vaddr += reloc->section_offset;
921 *out_start_val = start_val;
922 *out_end_val = end_val;
930 resolve_relocations (MonoAotCompile *acfg)
934 gsize end_val, start_val;
939 rr = g_new0 (ElfRelocA, acfg->num_relocs);
942 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
943 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
944 /* FIXME: little endian */
946 data [1] = end_val >> 8;
947 data [2] = end_val >> 16;
948 data [3] = end_val >> 24;
949 if (start_val == 0) {
950 rr [i].r_offset = vaddr;
951 rr [i].r_info = R_X86_64_RELATIVE;
952 rr [i].r_addend = end_val;
954 g_assert (i <= acfg->num_relocs);
960 #else /* USE_ELF_RELA */
963 do_reloc (MonoAotCompile *acfg, BinReloc *reloc, guint8 *data, gssize addr)
967 * We use the official ARM relocation types, but implement only the stuff actually
968 * needed by the code we generate.
970 switch (reloc->reloc_type) {
972 guint32 *code = (guint32*)(gpointer)data;
977 g_assert (data [3] == 0xeb);
978 if (diff >= 0 && diff <= 33554431) {
980 ins = (ins & 0xff000000) | diff;
982 } else if (diff <= 0 && diff >= -33554432) {
984 ins = (ins & 0xff000000) | (diff & ~0xff000000);
987 g_assert_not_reached ();
991 case R_ARM_ALU_PC_G0_NC: {
992 /* Generated by emit_plt () */
996 g_assert (val <= 0xffff);
997 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
998 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, (val & 0xFF00) >> 8, 24);
999 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, val & 0xFF);
1003 g_assert_not_reached ();
1006 g_assert_not_reached ();
1011 resolve_relocations (MonoAotCompile *acfg)
1015 gsize end_val, start_val;
1020 rr = g_new0 (ElfReloc, acfg->num_relocs);
1023 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
1024 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
1025 /* FIXME: little endian */
1026 if (reloc->reloc_type) {
1027 /* Must be static */
1028 g_assert (start_val > 0);
1029 do_reloc (acfg, reloc, data, end_val);
1032 data [1] = end_val >> 8;
1033 data [2] = end_val >> 16;
1034 data [3] = end_val >> 24;
1036 if (start_val == 0) {
1037 rr [i].r_offset = vaddr;
1038 rr [i].r_info = R_386_RELATIVE;
1040 g_assert (i <= acfg->num_relocs);
1046 #endif /* USE_ELF_RELA */
1049 emit_writeout (MonoAotCompile *acfg)
1051 char *outfile_name, *tmp_outfile_name;
1054 ElfProgHeader progh [3];
1055 ElfSectHeader secth [SECT_NUM];
1061 ElfStrTable str_table = {NULL, NULL};
1062 ElfStrTable sh_str_table = {NULL, NULL};
1063 ElfStrTable dyn_str_table = {NULL, NULL};
1064 BinSection* sections [6];
1065 BinSection *text_section = NULL, *data_section = NULL, *bss_section = NULL;
1068 ElfDynamic dynamic [14];
1070 int i, num_sections, file_offset, virt_offset, size, num_symtab;
1073 g_assert (!acfg->aot_opts.asm_only);
1075 if (acfg->aot_opts.outfile)
1076 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1078 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1080 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1082 unlink (tmp_outfile_name);
1083 file = fopen (tmp_outfile_name, "w");
1086 /* Section headers */
1087 memset (§h, 0, sizeof (secth));
1088 memset (&dynamic, 0, sizeof (dynamic));
1089 memset (&header, 0, sizeof (header));
1091 for (i = 1; i < SECT_NUM; ++i) {
1092 secth [i].sh_name = str_table_add (&sh_str_table, section_info [i].name);
1093 secth [i].sh_type = section_info [i].type;
1094 secth [i].sh_addralign = section_info [i].align;
1095 secth [i].sh_flags = section_info [i].flags;
1096 secth [i].sh_entsize = section_info [i].esize;
1098 secth [SECT_DYNSYM].sh_info = SIZEOF_VOID_P == 4 ? 4 : 2;
1099 secth [SECT_SYMTAB].sh_info = SIZEOF_VOID_P == 4 ? 20 : 17;
1100 secth [SECT_HASH].sh_link = SECT_DYNSYM;
1101 secth [SECT_DYNSYM].sh_link = SECT_DYNSTR;
1102 secth [SECT_REL_DYN].sh_link = SECT_DYNSYM;
1103 secth [SECT_RELA_DYN].sh_link = SECT_DYNSYM;
1104 secth [SECT_DYNAMIC].sh_link = SECT_DYNSTR;
1105 secth [SECT_SYMTAB].sh_link = SECT_STRTAB;
1107 num_sections = collect_sections (acfg, secth, sections, 6);
1108 hash = build_hash (acfg, num_sections, &dyn_str_table);
1109 num_symtab = hash [1]; /* FIXME */
1110 g_print ("num_sections: %d\n", num_sections);
1111 g_print ("dynsym: %d, dynstr size: %d\n", hash [1], (int)dyn_str_table.data->len);
1112 for (i = 0; i < num_sections; ++i) {
1113 g_print ("section %s, size: %d, %x\n", sections [i]->name, sections [i]->cur_offset, sections [i]->cur_offset);
1116 /* at this point we know where in the file the first segment sections go */
1117 dynsym = collect_syms (acfg, hash, &dyn_str_table, NULL, NULL);
1118 num_local_syms = hash [1];
1119 symtab = collect_syms (acfg, NULL, &str_table, secth, &num_local_syms);
1121 for (i = 0; i < num_sections; ++i) {
1122 if (sections [i]->shidx == SECT_TEXT) {
1123 text_section = sections [i];
1124 } else if (sections [i]->shidx == SECT_DATA) {
1125 data_section = sections [i];
1126 } else if (sections [i]->shidx == SECT_BSS) {
1127 bss_section = sections [i];
1131 file_offset = virt_offset = sizeof (header) + sizeof (progh);
1132 secth [SECT_HASH].sh_addr = secth [SECT_HASH].sh_offset = file_offset;
1133 size = sizeof (int) * (2 + hash [0] + hash [1]);
1134 virt_offset = (file_offset += size);
1135 secth [SECT_HASH].sh_size = size;
1136 secth [SECT_DYNSYM].sh_addr = secth [SECT_DYNSYM].sh_offset = file_offset;
1137 size = sizeof (ElfSymbol) * hash [1];
1138 virt_offset = (file_offset += size);
1139 secth [SECT_DYNSYM].sh_size = size;
1140 secth [SECT_DYNSTR].sh_addr = secth [SECT_DYNSTR].sh_offset = file_offset;
1141 size = dyn_str_table.data->len;
1142 virt_offset = (file_offset += size);
1143 secth [SECT_DYNSTR].sh_size = size;
1145 file_offset &= ~(4-1);
1146 secth [SECT_REL_DYN].sh_addr = secth [SECT_REL_DYN].sh_offset = file_offset;
1147 #ifndef USE_ELF_RELA
1148 size = sizeof (ElfReloc) * acfg->num_relocs;
1152 virt_offset = (file_offset += size);
1153 secth [SECT_REL_DYN].sh_size = size;
1154 secth [SECT_RELA_DYN].sh_addr = secth [SECT_RELA_DYN].sh_offset = file_offset;
1156 size = sizeof (ElfRelocA) * acfg->num_relocs;
1160 virt_offset = (file_offset += size);
1161 secth [SECT_RELA_DYN].sh_size = size;
1162 file_offset += 4096-1;
1163 file_offset &= ~(4096-1);
1164 virt_offset = file_offset;
1165 secth [SECT_TEXT].sh_addr = secth [SECT_TEXT].sh_offset = file_offset;
1166 size = text_section->cur_offset;
1167 secth [SECT_TEXT].sh_size = size;
1168 file_offset += size;
1170 file_offset &= ~(4-1);
1171 virt_offset = file_offset;
1172 /* .dynamic, .got.plt, .data, .bss here */
1173 /* Have to increase the virt offset since these go to a separate segment */
1174 virt_offset += PAGESIZE;
1175 secth [SECT_DYNAMIC].sh_addr = virt_offset;
1176 secth [SECT_DYNAMIC].sh_offset = file_offset;
1177 size = sizeof (dynamic);
1178 secth [SECT_DYNAMIC].sh_size = size;
1181 file_offset += size;
1182 virt_offset += size;
1183 secth [SECT_GOT_PLT].sh_addr = virt_offset;
1184 secth [SECT_GOT_PLT].sh_offset = file_offset;
1186 secth [SECT_GOT_PLT].sh_size = size;
1189 file_offset += size;
1190 virt_offset += size;
1191 secth [SECT_DATA].sh_addr = virt_offset;
1192 secth [SECT_DATA].sh_offset = file_offset;
1193 size = data_section->cur_offset;
1194 secth [SECT_DATA].sh_size = size;
1197 file_offset += size;
1198 virt_offset += size;
1199 secth [SECT_BSS].sh_addr = virt_offset;
1200 secth [SECT_BSS].sh_offset = file_offset;
1201 size = bss_section->cur_offset;
1202 secth [SECT_BSS].sh_size = size;
1204 /* virtual doesn't matter anymore */
1205 secth [SECT_SHSTRTAB].sh_offset = file_offset;
1206 size = sh_str_table.data->len;
1207 secth [SECT_SHSTRTAB].sh_size = size;
1208 size += SIZEOF_VOID_P-1;
1209 size &= ~(SIZEOF_VOID_P-1);
1210 file_offset += size;
1211 secth [SECT_SYMTAB].sh_offset = file_offset;
1212 size = sizeof (ElfSymbol) * num_local_syms;
1213 secth [SECT_SYMTAB].sh_size = size;
1214 file_offset += size;
1215 secth [SECT_STRTAB].sh_offset = file_offset;
1216 size = str_table.data->len;
1217 secth [SECT_STRTAB].sh_size = size;
1218 file_offset += size;
1220 file_offset &= ~(4-1);
1222 text_section->file_offset = secth [SECT_TEXT].sh_offset;
1223 text_section->virt_offset = secth [SECT_TEXT].sh_addr;
1224 data_section->file_offset = secth [SECT_DATA].sh_offset;
1225 data_section->virt_offset = secth [SECT_DATA].sh_addr;
1226 bss_section->file_offset = secth [SECT_BSS].sh_offset;
1227 bss_section->virt_offset = secth [SECT_BSS].sh_addr;
1229 header.e_ident [EI_MAG0] = ELFMAG0;
1230 header.e_ident [EI_MAG1] = ELFMAG1;
1231 header.e_ident [EI_MAG2] = ELFMAG2;
1232 header.e_ident [EI_MAG3] = ELFMAG3;
1233 header.e_ident [EI_CLASS] = SIZEOF_VOID_P == 4 ? ELFCLASS32 : ELFCLASS64;
1234 header.e_ident [EI_DATA] = ELFDATA2LSB;
1235 header.e_ident [EI_VERSION] = EV_CURRENT;
1236 header.e_ident [EI_OSABI] = ELFOSABI_NONE;
1237 header.e_ident [EI_ABIVERSION] = 0;
1238 for (i = EI_PAD; i < EI_NIDENT; ++i)
1239 header.e_ident [i] = 0;
1241 header.e_type = ET_DYN;
1242 #if defined(__i386__)
1243 header.e_machine = EM_386;
1244 #elif defined(__x86_64__)
1245 header.e_machine = EM_X86_64;
1246 #elif defined(__arm__)
1247 header.e_machine = EM_ARM;
1249 g_assert_not_reached ();
1251 header.e_version = 1;
1253 header.e_phoff = sizeof (header);
1254 header.e_ehsize = sizeof (header);
1255 header.e_phentsize = sizeof (ElfProgHeader);
1257 header.e_entry = secth [SECT_TEXT].sh_addr;
1258 header.e_shstrndx = SECT_SHSTRTAB;
1259 header.e_shentsize = sizeof (ElfSectHeader);
1260 header.e_shnum = SECT_NUM;
1261 header.e_shoff = file_offset;
1265 dynamic [i].d_tag = DT_HASH;
1266 dynamic [i].d_un.d_val = secth [SECT_HASH].sh_offset;
1268 dynamic [i].d_tag = DT_STRTAB;
1269 dynamic [i].d_un.d_val = secth [SECT_DYNSTR].sh_offset;
1271 dynamic [i].d_tag = DT_SYMTAB;
1272 dynamic [i].d_un.d_val = secth [SECT_DYNSYM].sh_offset;
1274 dynamic [i].d_tag = DT_STRSZ;
1275 dynamic [i].d_un.d_val = dyn_str_table.data->len;
1277 dynamic [i].d_tag = DT_SYMENT;
1278 dynamic [i].d_un.d_val = sizeof (ElfSymbol);
1281 dynamic [i].d_tag = DT_RELA;
1282 dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_offset;
1284 dynamic [i].d_tag = DT_RELASZ;
1285 dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_size;
1287 dynamic [i].d_tag = DT_RELAENT;
1288 dynamic [i].d_un.d_val = sizeof (ElfRelocA);
1291 dynamic [i].d_tag = DT_REL;
1292 dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_offset;
1294 dynamic [i].d_tag = DT_RELSZ;
1295 dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_size;
1297 dynamic [i].d_tag = DT_RELENT;
1298 dynamic [i].d_un.d_val = sizeof (ElfReloc);
1301 dynamic [i].d_tag = DT_RELCOUNT;
1302 dynamic [i].d_un.d_val = acfg->num_relocs;
1305 /* Program header */
1306 memset (&progh, 0, sizeof (progh));
1307 progh [0].p_type = PT_LOAD;
1308 progh [0].p_filesz = progh [0].p_memsz = secth [SECT_DYNAMIC].sh_offset;
1309 progh [0].p_align = 4096;
1310 progh [0].p_flags = 5;
1312 progh [1].p_type = PT_LOAD;
1313 progh [1].p_offset = secth [SECT_DYNAMIC].sh_offset;
1314 progh [1].p_vaddr = progh [1].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1315 progh [1].p_filesz = secth [SECT_BSS].sh_offset - secth [SECT_DYNAMIC].sh_offset;
1316 progh [1].p_memsz = secth [SECT_BSS].sh_addr + secth [SECT_BSS].sh_size - secth [SECT_DYNAMIC].sh_addr;
1317 progh [1].p_align = 4096;
1318 progh [1].p_flags = 6;
1320 progh [2].p_type = PT_DYNAMIC;
1321 progh [2].p_offset = secth [SECT_DYNAMIC].sh_offset;
1322 progh [2].p_vaddr = progh [2].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1323 progh [2].p_filesz = progh [2].p_memsz = secth [SECT_DYNAMIC].sh_size;
1324 progh [2].p_align = SIZEOF_VOID_P;
1325 progh [2].p_flags = 6;
1327 reloc_symbols (acfg, dynsym, secth, &dyn_str_table, TRUE);
1328 reloc_symbols (acfg, symtab, secth, &str_table, FALSE);
1329 relocs = resolve_relocations (acfg);
1331 fwrite (&header, sizeof (header), 1, file);
1332 fwrite (&progh, sizeof (progh), 1, file);
1333 fwrite (hash, sizeof (int) * (hash [0] + hash [1] + 2), 1, file);
1334 fwrite (dynsym, sizeof (ElfSymbol) * hash [1], 1, file);
1335 fwrite (dyn_str_table.data->str, dyn_str_table.data->len, 1, file);
1337 fseek (file, secth [SECT_REL_DYN].sh_offset, SEEK_SET);
1338 fwrite (relocs, sizeof (ElfReloc), acfg->num_relocs, file);
1341 fseek (file, secth [SECT_RELA_DYN].sh_offset, SEEK_SET);
1342 fwrite (relocs, secth [SECT_RELA_DYN].sh_size, 1, file);
1344 fseek (file, secth [SECT_TEXT].sh_offset, SEEK_SET);
1345 /* write .text, .data, .bss sections */
1346 fwrite (text_section->data, text_section->cur_offset, 1, file);
1349 fwrite (dynamic, sizeof (dynamic), 1, file);
1351 size = secth [SECT_DYNAMIC].sh_addr;
1352 fwrite (&size, sizeof (size), 1, file);
1353 fseek (file, secth [SECT_DATA].sh_offset, SEEK_SET);
1354 fwrite (data_section->data, data_section->cur_offset, 1, file);
1356 fseek (file, secth [SECT_SHSTRTAB].sh_offset, SEEK_SET);
1357 fwrite (sh_str_table.data->str, sh_str_table.data->len, 1, file);
1358 fseek (file, secth [SECT_SYMTAB].sh_offset, SEEK_SET);
1359 fwrite (symtab, sizeof (ElfSymbol) * num_local_syms, 1, file);
1360 fseek (file, secth [SECT_STRTAB].sh_offset, SEEK_SET);
1361 fwrite (str_table.data->str, str_table.data->len, 1, file);
1362 /*g_print ("file_offset %d vs %d\n", file_offset, ftell (file));*/
1363 /*g_assert (file_offset >= ftell (file));*/
1364 fseek (file, file_offset, SEEK_SET);
1365 fwrite (§h, sizeof (secth), 1, file);
1367 rename (tmp_outfile_name, outfile_name);
1369 g_free (tmp_outfile_name);
1370 g_free (outfile_name);
1375 #endif /* USE_ELF_WRITER */
1380 emit_start (MonoAotCompile *acfg)
1382 if (acfg->aot_opts.asm_only) {
1383 if (acfg->aot_opts.outfile)
1384 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1386 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
1387 acfg->fp = fopen (acfg->tmpfname, "w+");
1389 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
1390 acfg->fp = fdopen (i, "w+");
1392 g_assert (acfg->fp);
1396 emit_unset_mode (MonoAotCompile *acfg)
1398 if (acfg->mode == EMIT_NONE)
1400 fprintf (acfg->fp, "\n");
1401 acfg->mode = EMIT_NONE;
1405 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
1407 emit_unset_mode (acfg);
1408 #if defined(PLATFORM_WIN32)
1409 fprintf (acfg->fp, ".section %s\n", section_name);
1410 #elif defined(__MACH__)
1411 if (strcmp(section_name, ".bss") == 0)
1412 fprintf (acfg->fp, "%s\n", ".data");
1414 fprintf (acfg->fp, "%s\n", section_name);
1415 #elif defined(sparc) || defined(__arm__)
1416 /* For solaris as, GNU as should accept the same */
1417 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1419 fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1424 emit_symbol_type (MonoAotCompile *acfg, const char *name, gboolean func)
1433 emit_unset_mode (acfg);
1434 #if defined(__MACH__)
1436 #elif defined(sparc) || defined(__arm__)
1437 fprintf (acfg->fp, "\t.type %s,#%s\n", name, stype);
1438 #elif defined(PLATFORM_WIN32)
1440 #elif defined(__x86_64__) || defined(__i386__)
1441 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1443 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1448 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
1450 emit_unset_mode (acfg);
1451 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1452 // mach-o always uses a '_' prefix.
1453 fprintf (acfg->fp, "\t.globl _%s\n", name);
1455 fprintf (acfg->fp, "\t.globl %s\n", name);
1458 emit_symbol_type (acfg, name, func);
1462 emit_label (MonoAotCompile *acfg, const char *name)
1464 emit_unset_mode (acfg);
1465 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1466 // mach-o always uses a '_' prefix.
1467 fprintf (acfg->fp, "_%s:\n", name);
1469 fprintf (acfg->fp, "%s:\n", name);
1472 #if defined(PLATFORM_WIN32)
1473 /* Emit a normal label too */
1474 fprintf (acfg->fp, "%s:\n", name);
1479 emit_string (MonoAotCompile *acfg, const char *value)
1481 emit_unset_mode (acfg);
1482 fprintf (acfg->fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
1486 emit_line (MonoAotCompile *acfg)
1488 emit_unset_mode (acfg);
1489 fprintf (acfg->fp, "\n");
1493 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
1495 emit_unset_mode (acfg);
1496 emit_section_change (acfg, ".text", 1);
1497 emit_global (acfg, name, FALSE);
1498 emit_label (acfg, name);
1499 emit_string (acfg, value);
1503 emit_alignment (MonoAotCompile *acfg, int size)
1505 emit_unset_mode (acfg);
1506 #if defined(__arm__)
1507 fprintf (acfg->fp, "\t.align %d\n", ilog2 (size));
1508 #elif defined(__ppc__) && defined(__MACH__)
1509 // the mach-o assembler specifies alignments as powers of 2.
1510 fprintf (acfg->fp, "\t.align %d\t; ilog2\n", ilog2(size));
1511 #elif defined(__powerpc__)
1512 /* ignore on linux/ppc */
1514 fprintf (acfg->fp, "\t.align %d\n", size);
1519 emit_pointer (MonoAotCompile *acfg, const char *target)
1521 emit_unset_mode (acfg);
1522 emit_alignment (acfg, sizeof (gpointer));
1523 #if defined(__x86_64__)
1524 fprintf (acfg->fp, "\t.quad %s\n", target ? target : "0");
1525 #elif defined(sparc) && SIZEOF_VOID_P == 8
1526 fprintf (acfg->fp, "\t.xword %s\n", target ? target : "0");
1528 fprintf (acfg->fp, "\t.long %s\n", target ? target : "0");
1532 static char *byte_to_str;
1535 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
1538 if (acfg->mode != EMIT_BYTE) {
1539 acfg->mode = EMIT_BYTE;
1540 acfg->col_count = 0;
1543 if (byte_to_str == NULL) {
1544 byte_to_str = g_new0 (char, 256 * 8);
1545 for (i = 0; i < 256; ++i) {
1546 sprintf (byte_to_str + (i * 8), ",%d", i);
1550 for (i = 0; i < size; ++i, ++acfg->col_count) {
1551 if ((acfg->col_count % 32) == 0)
1552 fprintf (acfg->fp, "\n\t.byte %d", buf [i]);
1554 fputs (byte_to_str + (buf [i] * 8), acfg->fp);
1559 emit_int16 (MonoAotCompile *acfg, int value)
1561 if (acfg->mode != EMIT_WORD) {
1562 acfg->mode = EMIT_WORD;
1563 acfg->col_count = 0;
1565 if ((acfg->col_count++ % 8) == 0)
1566 #if defined(__MACH__)
1567 fprintf (acfg->fp, "\n\t.short ");
1568 #elif defined(__arm__)
1569 /* FIXME: Use .hword on other archs as well */
1570 fprintf (acfg->fp, "\n\t.hword ");
1572 fprintf (acfg->fp, "\n\t.word ");
1575 fprintf (acfg->fp, ", ");
1576 fprintf (acfg->fp, "%d", value);
1580 emit_int32 (MonoAotCompile *acfg, int value)
1582 if (acfg->mode != EMIT_LONG) {
1583 acfg->mode = EMIT_LONG;
1584 acfg->col_count = 0;
1586 if ((acfg->col_count++ % 8) == 0)
1587 fprintf (acfg->fp, "\n\t.long ");
1589 fprintf (acfg->fp, ",");
1590 fprintf (acfg->fp, "%d", value);
1594 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
1596 if (acfg->mode != EMIT_LONG) {
1597 acfg->mode = EMIT_LONG;
1598 acfg->col_count = 0;
1600 if ((acfg->col_count++ % 8) == 0)
1601 fprintf (acfg->fp, "\n\t.long ");
1603 fprintf (acfg->fp, ",");
1605 fprintf (acfg->fp, "%s - %s + %d", end, start, offset);
1606 else if (offset < 0)
1607 fprintf (acfg->fp, "%s - %s %d", end, start, offset);
1609 fprintf (acfg->fp, "%s - %s", end, start);
1613 emit_zero_bytes (MonoAotCompile *acfg, int num)
1615 emit_unset_mode (acfg);
1616 #if defined(__MACH__)
1617 fprintf (acfg->fp, "\t.space %d\n", num);
1619 fprintf (acfg->fp, "\t.skip %d\n", num);
1624 emit_writeout (MonoAotCompile *acfg)
1626 char *command, *objfile;
1627 char *outfile_name, *tmp_outfile_name;
1631 #if defined(__x86_64__)
1632 #define AS_OPTIONS "--64"
1633 #elif defined(sparc) && SIZEOF_VOID_P == 8
1634 #define AS_OPTIONS "-xarch=v9"
1636 #define AS_OPTIONS ""
1639 if (acfg->aot_opts.asm_only) {
1640 printf ("Output file: '%s'.\n", acfg->tmpfname);
1641 if (acfg->aot_opts.static_link)
1642 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1646 if (acfg->aot_opts.static_link) {
1647 if (acfg->aot_opts.outfile)
1648 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1650 objfile = g_strdup_printf ("%s.o", acfg->image->name);
1652 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
1654 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
1655 printf ("Executing the native assembler: %s\n", command);
1656 if (system (command) != 0) {
1664 if (acfg->aot_opts.static_link) {
1665 printf ("Output file: '%s'.\n", objfile);
1666 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1671 if (acfg->aot_opts.outfile)
1672 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1674 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1676 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1679 command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
1680 #elif defined(__ppc__) && defined(__MACH__)
1681 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
1682 #elif defined(PLATFORM_WIN32)
1683 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
1685 if (acfg->aot_opts.no_dlsym) {
1687 * Need to link using gcc so our ctor function gets called.
1689 command = g_strdup_printf ("gcc -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1691 command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1694 printf ("Executing the native linker: %s\n", command);
1695 if (system (command) != 0) {
1696 g_free (tmp_outfile_name);
1697 g_free (outfile_name);
1705 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
1706 printf ("Stripping the binary: %s\n", com);
1710 rename (tmp_outfile_name, outfile_name);
1712 g_free (tmp_outfile_name);
1713 g_free (outfile_name);
1716 if (acfg->aot_opts.save_temps)
1717 printf ("Retained input file.\n");
1719 unlink (acfg->tmpfname);
1724 #endif /* ASM_WRITER */
1727 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
1729 if (acfg->aot_opts.no_dlsym) {
1730 g_ptr_array_add (acfg->globals, g_strdup (name));
1732 emit_global_inner (acfg, name, func);
1737 emit_byte (MonoAotCompile *acfg, guint8 val)
1739 emit_bytes (acfg, &val, 1);
1743 mono_get_field_token (MonoClassField *field)
1745 MonoClass *klass = field->parent;
1748 for (i = 0; i < klass->field.count; ++i) {
1749 if (field == &klass->fields [i])
1750 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1753 g_assert_not_reached ();
1758 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1762 //printf ("ENCODE: %d 0x%x.\n", value, value);
1765 * Same encoding as the one used in the metadata, extended to handle values
1766 * greater than 0x1fffffff.
1768 if ((value >= 0) && (value <= 127))
1770 else if ((value >= 0) && (value <= 16383)) {
1771 p [0] = 0x80 | (value >> 8);
1772 p [1] = value & 0xff;
1774 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1775 p [0] = (value >> 24) | 0xc0;
1776 p [1] = (value >> 16) & 0xff;
1777 p [2] = (value >> 8) & 0xff;
1778 p [3] = value & 0xff;
1783 p [1] = (value >> 24) & 0xff;
1784 p [2] = (value >> 16) & 0xff;
1785 p [3] = (value >> 8) & 0xff;
1786 p [4] = value & 0xff;
1794 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1798 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1802 index = g_hash_table_size (cfg->image_hash);
1803 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1804 g_ptr_array_add (cfg->image_table, image);
1810 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1813 MonoClass *k = NULL;
1815 /* FIXME: Search referenced images as well */
1816 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1817 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1822 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1823 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1829 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1834 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1835 * standard metadata encoding.
1838 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1842 if (klass->generic_class) {
1844 g_assert (klass->type_token);
1846 /* Find a typespec for a class if possible */
1847 token = find_typespec_for_class (acfg, klass);
1849 encode_value (token, p, &p);
1850 encode_value (get_image_index (acfg, acfg->image), p, &p);
1852 MonoClass *gclass = klass->generic_class->container_class;
1853 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1856 /* Encode it ourselves */
1858 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1859 encode_value (MONO_TYPE_GENERICINST, p, &p);
1860 encode_klass_ref (acfg, gclass, p, &p);
1861 encode_value (inst->type_argc, p, &p);
1862 for (i = 0; i < inst->type_argc; ++i)
1863 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1865 } else if (klass->type_token) {
1866 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1867 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1868 encode_value (get_image_index (acfg, klass->image), p, &p);
1869 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1870 MonoGenericParam *param = klass->byval_arg.data.generic_param;
1873 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1874 encode_value (klass->byval_arg.type, p, &p);
1876 encode_value (param->num, p, &p);
1878 g_assert (param->owner);
1879 encode_value (param->owner->is_method, p, &p);
1880 if (param->owner->is_method)
1881 encode_method_ref (acfg, param->owner->owner.method, p, &p);
1883 encode_klass_ref (acfg, param->owner->owner.klass, p, &p);
1886 g_assert (klass->rank > 0);
1887 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1888 encode_value (get_image_index (acfg, klass->image), p, &p);
1889 encode_value (klass->rank, p, &p);
1890 encode_klass_ref (acfg, klass->element_class, p, &p);
1896 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1898 guint32 token = mono_get_field_token (field);
1901 encode_klass_ref (cfg, field->parent, p, &p);
1902 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1903 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1908 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1912 MonoGenericInst *inst;
1914 /* Encode the context */
1915 inst = context->class_inst;
1916 encode_value (inst ? 1 : 0, p, &p);
1918 encode_value (inst->type_argc, p, &p);
1919 for (i = 0; i < inst->type_argc; ++i)
1920 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1922 inst = context->method_inst;
1923 encode_value (inst ? 1 : 0, p, &p);
1925 encode_value (inst->type_argc, p, &p);
1926 for (i = 0; i < inst->type_argc; ++i)
1927 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1933 #define MAX_IMAGE_INDEX 250
1936 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1938 guint32 image_index = get_image_index (acfg, method->klass->image);
1939 guint32 token = method->token;
1940 MonoJumpInfoToken *ji;
1943 g_assert (image_index < MAX_IMAGE_INDEX);
1945 /* Mark methods which can't use aot trampolines because they need the further
1946 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1948 if (method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
1949 encode_value ((252 << 24), p, &p);
1951 if (method->wrapper_type) {
1953 encode_value ((253 << 24), p, &p);
1955 encode_value (method->wrapper_type, p, &p);
1957 switch (method->wrapper_type) {
1958 case MONO_WRAPPER_REMOTING_INVOKE:
1959 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1960 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1963 m = mono_marshal_method_from_wrapper (method);
1965 encode_method_ref (acfg, m, p, &p);
1968 case MONO_WRAPPER_PROXY_ISINST:
1969 case MONO_WRAPPER_LDFLD:
1970 case MONO_WRAPPER_LDFLDA:
1971 case MONO_WRAPPER_STFLD:
1972 case MONO_WRAPPER_ISINST: {
1973 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1974 encode_klass_ref (acfg, proxy_class, p, &p);
1977 case MONO_WRAPPER_LDFLD_REMOTE:
1978 case MONO_WRAPPER_STFLD_REMOTE:
1980 case MONO_WRAPPER_ALLOC: {
1981 int alloc_type = mono_gc_get_managed_allocator_type (method);
1982 g_assert (alloc_type != -1);
1983 encode_value (alloc_type, p, &p);
1986 case MONO_WRAPPER_STELEMREF:
1988 case MONO_WRAPPER_UNKNOWN:
1989 if (strcmp (method->name, "FastMonitorEnter") == 0)
1990 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1991 else if (strcmp (method->name, "FastMonitorExit") == 0)
1992 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1994 g_assert_not_reached ();
1996 case MONO_WRAPPER_STATIC_RGCTX_INVOKE: {
1999 m = mono_marshal_method_from_wrapper (method);
2001 encode_method_ref (acfg, m, p, &p);
2005 g_assert_not_reached ();
2007 } else if (mono_method_signature (method)->is_inflated) {
2009 * This is a generic method, find the original token which referenced it and
2011 * Obtain the token from information recorded by the JIT.
2013 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2015 image_index = get_image_index (acfg, ji->image);
2016 g_assert (image_index < MAX_IMAGE_INDEX);
2020 encode_value ((255 << 24), p, &p);
2021 encode_value (image_index, p, &p);
2022 encode_value (token, p, &p);
2024 MonoMethod *declaring;
2025 MonoGenericContext *context = mono_method_get_context (method);
2027 g_assert (method->is_inflated);
2028 declaring = ((MonoMethodInflated*)method)->declaring;
2031 * This might be a non-generic method of a generic instance, which
2032 * doesn't have a token since the reference is generated by the JIT
2033 * like Nullable:Box/Unbox, or by generic sharing.
2037 encode_value ((254 << 24), p, &p);
2038 /* Encode the klass */
2039 encode_klass_ref (acfg, method->klass, p, &p);
2040 /* Encode the method */
2041 image_index = get_image_index (acfg, method->klass->image);
2042 g_assert (image_index < MAX_IMAGE_INDEX);
2043 g_assert (declaring->token);
2044 token = declaring->token;
2045 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2046 encode_value (image_index, p, &p);
2047 encode_value (token, p, &p);
2048 encode_generic_context (acfg, context, p, &p);
2050 } else if (token == 0) {
2051 /* This might be a method of a constructed type like int[,].Set */
2052 /* Obtain the token from information recorded by the JIT */
2053 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2055 image_index = get_image_index (acfg, ji->image);
2056 g_assert (image_index < MAX_IMAGE_INDEX);
2060 encode_value ((255 << 24), p, &p);
2061 encode_value (image_index, p, &p);
2062 encode_value (token, p, &p);
2064 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2065 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2071 compare_patches (gconstpointer a, gconstpointer b)
2075 i = (*(MonoJumpInfo**)a)->ip.i;
2076 j = (*(MonoJumpInfo**)b)->ip.i;
2090 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2093 static inline gboolean
2094 is_plt_patch (MonoJumpInfo *patch_info)
2096 switch (patch_info->type) {
2097 case MONO_PATCH_INFO_METHOD:
2098 case MONO_PATCH_INFO_INTERNAL_METHOD:
2099 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2100 case MONO_PATCH_INFO_CLASS_INIT:
2101 case MONO_PATCH_INFO_RGCTX_FETCH:
2102 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2103 case MONO_PATCH_INFO_MONITOR_ENTER:
2104 case MONO_PATCH_INFO_MONITOR_EXIT:
2112 * is_shared_got_patch:
2114 * Return whenever PATCH_INFO refers to a patch which needs a shared GOT
2116 * Keep it in sync with the version in aot-runtime.c.
2118 static inline gboolean
2119 is_shared_got_patch (MonoJumpInfo *patch_info)
2121 switch (patch_info->type) {
2122 case MONO_PATCH_INFO_VTABLE:
2123 case MONO_PATCH_INFO_CLASS:
2124 case MONO_PATCH_INFO_IID:
2125 case MONO_PATCH_INFO_ADJUSTED_IID:
2126 case MONO_PATCH_INFO_FIELD:
2127 case MONO_PATCH_INFO_SFLDA:
2128 case MONO_PATCH_INFO_DECLSEC:
2129 case MONO_PATCH_INFO_LDTOKEN:
2130 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2131 case MONO_PATCH_INFO_RVA:
2132 case MONO_PATCH_INFO_METHODCONST:
2140 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2144 if (is_plt_patch (patch_info)) {
2145 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
2150 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2152 res = acfg->plt_offset;
2153 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
2154 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
2155 acfg->plt_offset ++;
2165 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2166 * JI could be found if it exists, otherwise allocates a new one.
2169 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2173 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
2175 return got_offset - 1;
2177 got_offset = acfg->got_offset;
2178 acfg->got_offset ++;
2180 acfg->stats.got_slots ++;
2181 acfg->stats.got_slot_types [ji->type] ++;
2187 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2192 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
2193 got_offset = get_got_offset (acfg, ji);
2194 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
2195 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
2196 g_ptr_array_add (acfg->shared_patches, copy);
2199 return get_got_offset (acfg, ji);
2202 /* Add a method to the list of methods which need to be emitted */
2204 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
2207 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2208 g_ptr_array_add (acfg->methods, method);
2209 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2210 acfg->nmethods = acfg->methods->len + 1;
2215 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2217 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2225 add_method (MonoAotCompile *acfg, MonoMethod *method)
2229 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2233 index = acfg->method_index;
2234 add_method_with_index (acfg, method, index);
2236 /* FIXME: Fix quadratic behavior */
2237 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2239 acfg->method_index ++;
2245 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2249 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2252 add_method (acfg, method);
2253 g_ptr_array_add (acfg->extra_methods, method);
2257 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2259 MonoAotCompile *acfg = user_data;
2260 MonoJitICallInfo *callinfo = value;
2261 MonoMethod *wrapper;
2267 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2268 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2271 add_method (acfg, wrapper);
2275 get_runtime_invoke_sig (MonoMethodSignature *sig)
2277 MonoMethodBuilder *mb;
2280 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2281 m = mono_mb_create_method (mb, sig, 16);
2282 return mono_marshal_get_runtime_invoke (m);
2286 add_wrappers (MonoAotCompile *acfg)
2288 MonoMethod *method, *m;
2289 int i, j, nallocators;
2290 MonoMethodSignature *sig, *csig;
2294 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2295 * so there is only one wrapper of a given type, or inlining their contents into their
2300 * FIXME: This depends on the fact that different wrappers have different
2304 /* FIXME: Collect these automatically */
2306 /* Runtime invoke wrappers */
2308 /* void runtime-invoke () [.cctor] */
2309 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2310 csig->ret = &mono_defaults.void_class->byval_arg;
2311 add_method (acfg, get_runtime_invoke_sig (csig));
2313 /* void runtime-invoke () [Finalize] */
2314 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2316 csig->ret = &mono_defaults.void_class->byval_arg;
2317 add_method (acfg, get_runtime_invoke_sig (csig));
2319 /* void runtime-invoke (string) [exception ctor] */
2320 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2322 csig->ret = &mono_defaults.void_class->byval_arg;
2323 csig->params [0] = &mono_defaults.string_class->byval_arg;
2324 add_method (acfg, get_runtime_invoke_sig (csig));
2326 /* void runtime-invoke (string, string) [exception ctor] */
2327 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2329 csig->ret = &mono_defaults.void_class->byval_arg;
2330 csig->params [0] = &mono_defaults.string_class->byval_arg;
2331 csig->params [1] = &mono_defaults.string_class->byval_arg;
2332 add_method (acfg, get_runtime_invoke_sig (csig));
2334 /* string runtime-invoke () [Exception.ToString ()] */
2335 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2337 csig->ret = &mono_defaults.string_class->byval_arg;
2338 add_method (acfg, get_runtime_invoke_sig (csig));
2340 /* void runtime-invoke (string, Exception) [exception ctor] */
2341 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2343 csig->ret = &mono_defaults.void_class->byval_arg;
2344 csig->params [0] = &mono_defaults.string_class->byval_arg;
2345 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2346 add_method (acfg, get_runtime_invoke_sig (csig));
2348 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2349 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2351 csig->ret = &(mono_class_from_name (
2352 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2353 csig->params [0] = &mono_defaults.string_class->byval_arg;
2354 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2355 add_method (acfg, get_runtime_invoke_sig (csig));
2357 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2359 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2360 gboolean skip = FALSE;
2362 method = mono_get_method (acfg->image, token, NULL);
2364 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2365 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2366 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2369 if (method->is_generic || method->klass->generic_container)
2372 /* Skip methods which can not be handled by get_runtime_invoke () */
2373 sig = mono_method_signature (method);
2374 if ((sig->ret->type == MONO_TYPE_PTR) ||
2375 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2378 for (j = 0; j < sig->param_count; j++) {
2379 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2384 add_method (acfg, mono_marshal_get_runtime_invoke (method));
2387 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2388 MonoMethodDesc *desc;
2389 MonoMethod *orig_method;
2391 /* JIT icall wrappers */
2392 /* FIXME: locking */
2393 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2395 /* Managed Allocators */
2396 nallocators = mono_gc_get_managed_allocator_types ();
2397 for (i = 0; i < nallocators; ++i) {
2398 m = mono_gc_get_managed_allocator_by_type (i);
2400 add_method (acfg, m);
2404 add_method (acfg, mono_marshal_get_stelemref ());
2406 /* Monitor Enter/Exit */
2407 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2408 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2409 g_assert (orig_method);
2410 mono_method_desc_free (desc);
2411 method = mono_monitor_get_fast_path (orig_method);
2413 add_method (acfg, method);
2415 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2416 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2417 g_assert (orig_method);
2418 mono_method_desc_free (desc);
2419 method = mono_monitor_get_fast_path (orig_method);
2421 add_method (acfg, method);
2424 /* remoting-invoke wrappers */
2425 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2426 MonoMethodSignature *sig;
2428 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2429 method = mono_get_method (acfg->image, token, NULL);
2431 sig = mono_method_signature (method);
2433 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
2434 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2435 m = mono_marshal_get_remoting_invoke_with_check (method);
2437 add_method (acfg, m);
2441 /* delegate-invoke wrappers */
2442 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2445 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2446 klass = mono_class_get (acfg->image, token);
2448 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2449 method = mono_get_delegate_invoke (klass);
2451 m = mono_marshal_get_delegate_invoke (method, NULL);
2453 add_method (acfg, m);
2458 /* static rgctx wrappers */
2459 /* FIXME: Each wrapper belongs to a given instantiation of a generic method */
2460 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2461 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2462 method = mono_get_method (acfg->image, token, NULL);
2464 if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
2465 (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
2466 mono_class_generic_sharing_enabled (method->klass) &&
2467 mono_method_is_generic_sharable_impl (method, FALSE)) {
2468 m = mono_marshal_get_static_rgctx_invoke (method);
2469 add_method (acfg, m);
2476 has_type_vars (MonoClass *klass)
2478 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2481 return has_type_vars (klass->element_class);
2482 if (klass->generic_class) {
2483 MonoGenericContext *context = &klass->generic_class->context;
2484 if (context->class_inst) {
2487 for (i = 0; i < context->class_inst->type_argc; ++i)
2488 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2496 method_has_type_vars (MonoMethod *method)
2498 if (has_type_vars (method->klass))
2501 if (method->is_inflated) {
2502 MonoGenericContext *context = mono_method_get_context (method);
2503 if (context->method_inst) {
2506 for (i = 0; i < context->method_inst->type_argc; ++i)
2507 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2515 * add_generic_instances:
2517 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2520 add_generic_instances (MonoAotCompile *acfg)
2525 MonoGenericContext *context;
2527 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2528 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2529 method = mono_get_method (acfg->image, token, NULL);
2531 context = mono_method_get_context (method);
2532 if (context && ((context->class_inst && context->class_inst->is_open) ||
2533 (context->method_inst && context->method_inst->is_open)))
2536 if (method->klass->image != acfg->image)
2539 if (mono_method_is_generic_sharable_impl (method, FALSE))
2543 add_extra_method (acfg, method);
2546 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2550 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2552 klass = mono_class_get (acfg->image, token);
2555 mono_class_init (klass);
2557 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2560 if (has_type_vars (klass))
2564 * Add rgctx wrappers for cctors since those are called by the runtime, so
2565 * there is no methodspec for them. This is needed even for shared classes,
2566 * since rgctx wrappers belong to inflated methods.
2568 method = mono_class_get_cctor (klass);
2570 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
2573 while ((method = mono_class_get_methods (klass, &iter))) {
2574 if (mono_method_is_generic_sharable_impl (method, FALSE))
2578 if (method->is_generic)
2583 * FIXME: Instances which are referenced by these methods are not added,
2584 * for example Array.Resize<int> for List<int>.Add ().
2586 add_extra_method (acfg, method);
2592 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2594 int i, pindex, start_index, method_index;
2596 MonoJumpInfo *patch_info;
2597 MonoMethodHeader *header;
2598 gboolean skip, direct_call;
2600 char direct_call_target [128];
2603 header = mono_method_get_header (method);
2605 method_index = get_method_index (acfg, method);
2608 /* Collect and sort relocations */
2609 patches = g_ptr_array_new ();
2610 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2611 g_ptr_array_add (patches, patch_info);
2612 g_ptr_array_sort (patches, compare_patches);
2615 for (i = 0; i < code_len; i++) {
2617 for (pindex = start_index; pindex < patches->len; ++pindex) {
2618 patch_info = g_ptr_array_index (patches, pindex);
2619 if (patch_info->ip.i >= i)
2623 #ifdef MONO_ARCH_AOT_SUPPORTED
2625 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2626 start_index = pindex;
2628 switch (patch_info->type) {
2629 case MONO_PATCH_INFO_NONE:
2631 case MONO_PATCH_INFO_GOT_OFFSET: {
2632 guint32 offset = mono_arch_get_patch_offset (code + i);
2633 emit_bytes (acfg, code + i, offset);
2634 emit_symbol_diff (acfg, "got", ".", offset);
2636 i += offset + 4 - 1;
2641 if (!is_got_patch (patch_info->type))
2645 * If this patch is a call, try emitting a direct call instead of
2646 * through a PLT entry. This is possible if the called method is in
2647 * the same assembly and requires no initialization.
2649 direct_call = FALSE;
2650 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
2651 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2653 gboolean direct_callable = TRUE;
2655 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2656 direct_callable = FALSE;
2657 if (direct_callable) {
2658 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2660 sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
2661 patch_info->type = MONO_PATCH_INFO_NONE;
2662 acfg->stats.direct_calls ++;
2666 acfg->stats.all_calls ++;
2669 if (!got_only && !direct_call) {
2670 int plt_offset = get_plt_offset (acfg, patch_info);
2671 if (plt_offset != -1) {
2672 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2674 sprintf (direct_call_target, ".Lp_%d", plt_offset);
2676 /* Nullify the patch */
2677 patch_info->type = MONO_PATCH_INFO_NONE;
2682 #if defined(__i386__) || defined(__x86_64__)
2683 g_assert (code [i] == 0xe8);
2684 /* Need to make sure this is exactly 5 bytes long */
2685 emit_byte (acfg, '\xe8');
2686 emit_symbol_diff (acfg, direct_call_target, ".", -4);
2688 #elif defined(__arm__)
2689 #ifdef USE_BIN_WRITER
2697 emit_reloc (acfg, R_ARM_CALL, direct_call_target, -8);
2698 emit_bytes (acfg, buf, 4);
2701 emit_unset_mode (acfg);
2702 fprintf (acfg->fp, "bl %s\n", direct_call_target);
2706 g_assert_not_reached ();
2709 got_slot = get_got_offset (acfg, patch_info);
2711 emit_bytes (acfg, code + i, mono_arch_get_patch_offset (code + i));
2713 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
2714 #elif defined(__i386__)
2715 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
2716 #elif defined(__arm__)
2717 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
2719 g_assert_not_reached ();
2722 i += mono_arch_get_patch_offset (code + i) + 4 - 1;
2728 #endif /* MONO_ARCH_AOT_SUPPORTED */
2731 /* Find next patch */
2733 for (pindex = start_index; pindex < patches->len; ++pindex) {
2734 patch_info = g_ptr_array_index (patches, pindex);
2735 if (patch_info->ip.i >= i)
2739 /* Try to emit multiple bytes at once */
2740 if (pindex < patches->len && patch_info->ip.i > i) {
2741 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2742 i = patch_info->ip.i - 1;
2744 emit_bytes (acfg, code + i, 1);
2751 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2757 int func_alignment = 16;
2758 MonoMethodHeader *header;
2760 method = cfg->orig_method;
2761 code = cfg->native_code;
2762 header = mono_method_get_header (method);
2764 method_index = get_method_index (acfg, method);
2766 /* Make the labels local */
2767 sprintf (symbol, ".Lm_%x", method_index);
2769 emit_alignment (acfg, func_alignment);
2770 emit_label (acfg, symbol);
2771 if (acfg->aot_opts.write_symbols)
2772 emit_global (acfg, symbol, TRUE);
2774 if (cfg->verbose_level > 0)
2775 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2777 acfg->stats.code_size += cfg->code_len;
2779 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2781 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2789 * Encode PATCH_INFO into its disk representation.
2792 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2796 switch (patch_info->type) {
2797 case MONO_PATCH_INFO_NONE:
2799 case MONO_PATCH_INFO_IMAGE:
2800 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2802 case MONO_PATCH_INFO_METHOD_REL:
2803 encode_value ((gint)patch_info->data.offset, p, &p);
2805 case MONO_PATCH_INFO_SWITCH: {
2806 gpointer *table = (gpointer *)patch_info->data.table->table;
2809 encode_value (patch_info->data.table->table_size, p, &p);
2810 for (k = 0; k < patch_info->data.table->table_size; k++)
2811 encode_value ((int)(gssize)table [k], p, &p);
2814 case MONO_PATCH_INFO_METHODCONST:
2815 case MONO_PATCH_INFO_METHOD:
2816 case MONO_PATCH_INFO_METHOD_JUMP:
2817 case MONO_PATCH_INFO_ICALL_ADDR:
2818 case MONO_PATCH_INFO_METHOD_RGCTX:
2819 encode_method_ref (acfg, patch_info->data.method, p, &p);
2821 case MONO_PATCH_INFO_INTERNAL_METHOD:
2822 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2823 guint32 len = strlen (patch_info->data.name);
2825 encode_value (len, p, &p);
2827 memcpy (p, patch_info->data.name, len);
2832 case MONO_PATCH_INFO_LDSTR: {
2833 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2834 guint32 token = patch_info->data.token->token;
2835 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2836 encode_value (image_index, p, &p);
2837 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2840 case MONO_PATCH_INFO_RVA:
2841 case MONO_PATCH_INFO_DECLSEC:
2842 case MONO_PATCH_INFO_LDTOKEN:
2843 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2844 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2845 encode_value (patch_info->data.token->token, p, &p);
2846 encode_value (patch_info->data.token->has_context, p, &p);
2847 if (patch_info->data.token->has_context)
2848 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2850 case MONO_PATCH_INFO_EXC_NAME: {
2851 MonoClass *ex_class;
2854 mono_class_from_name (mono_defaults.exception_class->image,
2855 "System", patch_info->data.target);
2856 g_assert (ex_class);
2857 encode_klass_ref (acfg, ex_class, p, &p);
2860 case MONO_PATCH_INFO_R4:
2861 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2863 case MONO_PATCH_INFO_R8:
2864 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2865 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2867 case MONO_PATCH_INFO_VTABLE:
2868 case MONO_PATCH_INFO_CLASS:
2869 case MONO_PATCH_INFO_IID:
2870 case MONO_PATCH_INFO_ADJUSTED_IID:
2871 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2873 case MONO_PATCH_INFO_CLASS_INIT:
2874 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2875 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2877 case MONO_PATCH_INFO_FIELD:
2878 case MONO_PATCH_INFO_SFLDA:
2879 encode_field_info (acfg, patch_info->data.field, p, &p);
2881 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2883 case MONO_PATCH_INFO_RGCTX_FETCH: {
2884 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2886 encode_method_ref (acfg, entry->method, p, &p);
2887 encode_value (entry->in_mrgctx, p, &p);
2888 encode_value (entry->info_type, p, &p);
2889 encode_value (entry->data->type, p, &p);
2890 encode_patch (acfg, entry->data, p, &p);
2893 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2894 case MONO_PATCH_INFO_MONITOR_ENTER:
2895 case MONO_PATCH_INFO_MONITOR_EXIT:
2898 g_warning ("unable to handle jump info %d", patch_info->type);
2899 g_assert_not_reached ();
2906 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2909 guint32 last_offset, j, pindex;
2910 MonoJumpInfo *patch_info;
2912 encode_value (n_patches, p, &p);
2915 encode_value (first_got_offset, p, &p);
2917 /* First encode the type+position table */
2920 for (pindex = 0; pindex < patches->len; ++pindex) {
2922 patch_info = g_ptr_array_index (patches, pindex);
2924 if (patch_info->type == MONO_PATCH_INFO_NONE)
2929 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
2930 offset = patch_info->ip.i - last_offset;
2931 last_offset = patch_info->ip.i;
2933 /* Only the type is needed */
2934 *p = patch_info->type;
2938 /* Then encode the other info */
2939 for (pindex = 0; pindex < patches->len; ++pindex) {
2940 patch_info = g_ptr_array_index (patches, pindex);
2942 if (is_shared_got_patch (patch_info)) {
2943 guint32 offset = get_got_offset (acfg, patch_info);
2944 encode_value (offset, p, &p);
2946 encode_patch (acfg, patch_info, p, &p);
2954 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2958 int pindex, buf_size, n_patches;
2962 MonoJumpInfo *patch_info;
2963 MonoMethodHeader *header;
2964 guint32 method_index;
2966 guint32 first_got_offset;
2968 method = cfg->orig_method;
2969 code = cfg->native_code;
2970 header = mono_method_get_header (method);
2972 method_index = get_method_index (acfg, method);
2974 /* Make the labels local */
2975 sprintf (symbol, ".Lm_%x_p", method_index);
2977 /* Sort relocations */
2978 patches = g_ptr_array_new ();
2979 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2980 g_ptr_array_add (patches, patch_info);
2981 g_ptr_array_sort (patches, compare_patches);
2983 first_got_offset = acfg->cfgs [method_index]->got_offset;
2985 /**********************/
2986 /* Encode method info */
2987 /**********************/
2989 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2990 p = buf = g_malloc (buf_size);
2992 if (mono_class_get_cctor (method->klass))
2993 encode_klass_ref (acfg, method->klass, p, &p);
2995 /* Not needed when loading the method */
2996 encode_value (0, p, &p);
2999 if (cfg->opt & MONO_OPT_SHARED) {
3000 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3001 for (l = cfg->ldstr_list; l; l = l->next) {
3002 encode_value ((long)l->data, p, &p);
3006 /* Used only in shared mode */
3007 g_assert (!cfg->ldstr_list);
3010 for (pindex = 0; pindex < patches->len; ++pindex) {
3011 patch_info = g_ptr_array_index (patches, pindex);
3013 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3014 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3015 patch_info->type = MONO_PATCH_INFO_NONE;
3020 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3021 /* Stored in a GOT slot initialized at module load time */
3022 patch_info->type = MONO_PATCH_INFO_NONE;
3026 if (is_plt_patch (patch_info)) {
3027 /* Calls are made through the PLT */
3028 patch_info->type = MONO_PATCH_INFO_NONE;
3036 g_assert (cfg->has_got_slots);
3038 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3040 acfg->stats.info_size += p - buf;
3042 /* Emit method info */
3044 emit_label (acfg, symbol);
3046 g_assert (p - buf < buf_size);
3047 emit_bytes (acfg, buf, p - buf);
3052 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3055 int k, buf_size, method_index;
3056 guint32 debug_info_size;
3059 MonoMethodHeader *header;
3060 guint8 *p, *buf, *debug_info;
3061 MonoJitInfo *jinfo = cfg->jit_info;
3063 method = cfg->orig_method;
3064 code = cfg->native_code;
3065 header = mono_method_get_header (method);
3067 method_index = get_method_index (acfg, method);
3069 /* Make the labels local */
3070 sprintf (symbol, ".Le_%x_p", method_index);
3072 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3074 buf_size = header->num_clauses * 256 + debug_info_size + 128;
3075 p = buf = g_malloc (buf_size);
3077 encode_value (jinfo->code_size, p, &p);
3078 encode_value (jinfo->used_regs, p, &p);
3079 encode_value (jinfo->has_generic_jit_info, p, &p);
3081 /* Exception table */
3082 if (header->num_clauses) {
3083 for (k = 0; k < header->num_clauses; ++k) {
3084 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3086 encode_value (ei->exvar_offset, p, &p);
3088 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
3089 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3091 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3092 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3093 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3097 if (jinfo->has_generic_jit_info) {
3098 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3100 encode_value (gi->has_this ? 1 : 0, p, &p);
3101 encode_value (gi->this_reg, p, &p);
3102 encode_value (gi->this_offset, p, &p);
3105 * Need to encode jinfo->method too, since it is not equal to 'method'
3106 * when using generic sharing.
3108 encode_method_ref (acfg, jinfo->method, p, &p);
3111 g_assert (debug_info_size < buf_size);
3113 encode_value (debug_info_size, p, &p);
3114 if (debug_info_size) {
3115 memcpy (p, debug_info, debug_info_size);
3116 p += debug_info_size;
3117 g_free (debug_info);
3120 acfg->stats.ex_info_size += p - buf;
3124 emit_label (acfg, symbol);
3126 g_assert (p - buf < buf_size);
3127 emit_bytes (acfg, buf, p - buf);
3132 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3134 MonoClass *klass = mono_class_get (acfg->image, token);
3138 gboolean no_special_static, cant_encode;
3139 gpointer iter = NULL;
3141 buf_size = 10240 + (klass->vtable_size * 16);
3142 p = buf = g_malloc (buf_size);
3146 mono_class_init (klass);
3148 mono_class_get_nested_types (klass, &iter);
3149 g_assert (klass->nested_classes_inited);
3151 mono_class_setup_vtable (klass);
3154 * Emit all the information which is required for creating vtables so
3155 * the runtime does not need to create the MonoMethod structures which
3156 * take up a lot of space.
3159 no_special_static = !mono_class_has_special_static_fields (klass);
3161 /* Check whenever we have enough info to encode the vtable */
3162 cant_encode = FALSE;
3163 for (i = 0; i < klass->vtable_size; ++i) {
3164 MonoMethod *cm = klass->vtable [i];
3166 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3170 if (klass->generic_container || cant_encode) {
3171 encode_value (-1, p, &p);
3173 encode_value (klass->vtable_size, p, &p);
3174 encode_value ((no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | (klass->nested_classes ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
3175 if (klass->has_cctor)
3176 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3177 if (klass->has_finalize)
3178 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3180 encode_value (klass->instance_size, p, &p);
3181 encode_value (mono_class_data_size (klass), p, &p);
3182 encode_value (klass->packing_size, p, &p);
3183 encode_value (klass->min_align, p, &p);
3185 for (i = 0; i < klass->vtable_size; ++i) {
3186 MonoMethod *cm = klass->vtable [i];
3189 encode_method_ref (acfg, cm, p, &p);
3191 encode_value (0, p, &p);
3195 acfg->stats.class_info_size += p - buf;
3198 sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
3199 emit_label (acfg, symbol);
3201 g_assert (p - buf < buf_size);
3202 emit_bytes (acfg, buf, p - buf);
3207 * Calls made from AOTed code are routed through a table of jumps similar to the
3208 * ELF PLT (Program Linkage Table). The differences are the following:
3209 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3210 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3211 * jumps. This means the jumps need to be patched when the address of the callee is
3212 * known. Initially the PLT entries jump to code which transfers control to the
3213 * AOT runtime through the first PLT entry.
3216 emit_plt (MonoAotCompile *acfg)
3221 guint32 *plt_info_offsets;
3224 * Encode info need to resolve PLT entries.
3226 buf_size = acfg->plt_offset * 128;
3227 p = buf = g_malloc (buf_size);
3229 plt_info_offsets = g_new0 (guint32, acfg->plt_offset);
3231 for (i = 1; i < acfg->plt_offset; ++i) {
3232 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3234 plt_info_offsets [i] = p - buf;
3235 encode_value (patch_info->type, p, &p);
3236 encode_patch (acfg, patch_info, p, &p);
3240 sprintf (symbol, "plt");
3242 emit_section_change (acfg, ".text", 0);
3243 emit_global (acfg, symbol, TRUE);
3245 /* This section will be made read-write by the AOT loader */
3246 emit_alignment (acfg, PAGESIZE);
3248 emit_alignment (acfg, 16);
3250 emit_label (acfg, symbol);
3252 for (i = 0; i < acfg->plt_offset; ++i) {
3254 #if defined(__arm__)
3259 sprintf (label, ".Lp_%d", i);
3260 emit_label (acfg, label);
3263 * The first plt entry is used to transfer code to the AOT loader.
3266 #if defined(__i386__)
3268 /* It is filled up during loading by the AOT loader. */
3269 emit_zero_bytes (acfg, 16);
3271 /* Need to make sure this is 9 bytes long */
3272 emit_byte (acfg, '\xe9');
3273 emit_symbol_diff (acfg, "plt", ".", -4);
3274 emit_int32 (acfg, plt_info_offsets [i]);
3276 #elif defined(__x86_64__)
3278 * We can't emit jumps because they are 32 bits only so they can't be patched.
3279 * So we emit a jump table instead whose entries are patched by the AOT loader to
3280 * point to .Lpd entries. ELF stores these in the GOT too, but we don't, since
3281 * methods with GOT entries can't be called directly.
3282 * We also emit the default PLT code here since the PLT code will not be patched.
3283 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
3285 /* jmpq *<offset>(%rip) */
3286 emit_byte (acfg, '\xff');
3287 emit_byte (acfg, '\x25');
3288 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)) -4);
3289 /* Used by mono_aot_get_plt_info_offset */
3290 emit_int32 (acfg, plt_info_offsets [i]);
3291 #elif defined(__arm__)
3293 * - optimize OP_AOTCONST implementation
3294 * - optimize the PLT entries
3295 * - optimize SWITCH AOT implementation
3296 * - implement IMT support
3299 #ifdef USE_BIN_WRITER
3300 /* We only emit 1 relocation since we implement it ourselves anyway */
3301 emit_reloc (acfg, R_ARM_ALU_PC_G0_NC, "plt_jump_table", (i * sizeof (gpointer)) - 8);
3302 /* FIXME: A 2 instruction encoding is sufficient in most cases */
3303 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
3304 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
3305 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
3306 emit_bytes (acfg, buf, code - buf);
3307 /* FIXME: Get rid of this */
3308 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)));
3309 /* Used by mono_aot_get_plt_info_offset */
3310 emit_int32 (acfg, plt_info_offsets [i]);
3312 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
3313 ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
3314 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
3315 emit_bytes (acfg, buf, code - buf);
3316 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)));
3317 /* Used by mono_aot_get_plt_info_offset */
3318 emit_int32 (acfg, plt_info_offsets [i]);
3322 g_assert_not_reached ();
3326 g_free (plt_info_offsets);
3328 sprintf (symbol, "plt_end");
3329 emit_global (acfg, symbol, TRUE);
3330 emit_label (acfg, symbol);
3333 sprintf (symbol, "plt_info");
3334 emit_global (acfg, symbol, FALSE);
3335 emit_label (acfg, symbol);
3337 g_assert (p - buf < buf_size);
3338 emit_bytes (acfg, buf, p - buf);
3341 sprintf (symbol, "plt_jump_table_addr");
3342 emit_section_change (acfg, ".data", 0);
3343 emit_global (acfg, symbol, FALSE);
3344 emit_alignment (acfg, 8);
3345 emit_label (acfg, symbol);
3346 emit_pointer (acfg, "plt_jump_table");
3348 sprintf (symbol, "plt_jump_table_size");
3349 emit_section_change (acfg, ".data", 0);
3350 emit_global (acfg, symbol, FALSE);
3351 emit_alignment (acfg, 8);
3352 emit_label (acfg, symbol);
3353 emit_symbol_diff (acfg, "plt_jump_table_end", "plt_jump_table", 0);
3355 /* Don't make this a global so accesses don't need relocations */
3356 sprintf (symbol, "plt_jump_table");
3357 emit_section_change (acfg, ".bss", 0);
3358 emit_label (acfg, symbol);
3360 #if defined(__x86_64__) || defined(__arm__)
3361 emit_zero_bytes (acfg, (int)(acfg->plt_offset * sizeof (gpointer)));
3364 sprintf (symbol, "plt_jump_table_end");
3365 emit_label (acfg, symbol);
3368 static G_GNUC_UNUSED void
3369 emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code,
3370 guint32 code_size, int got_offset, MonoJumpInfo *ji)
3374 MonoJumpInfo *patch_info;
3380 sprintf (symbol, "%s", name);
3382 emit_section_change (acfg, ".text", 0);
3383 emit_global (acfg, symbol, TRUE);
3384 emit_alignment (acfg, 16);
3385 emit_label (acfg, symbol);
3388 * The code should access everything through the GOT, so we pass
3391 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3395 /* Sort relocations */
3396 patches = g_ptr_array_new ();
3397 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3398 g_ptr_array_add (patches, patch_info);
3399 g_ptr_array_sort (patches, compare_patches);
3401 buf_size = patches->len * 128 + 128;
3402 buf = g_malloc (buf_size);
3405 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3406 g_assert (p - buf < buf_size);
3408 sprintf (symbol, "%s_p", name);
3410 emit_section_change (acfg, ".text", 0);
3411 emit_global (acfg, symbol, FALSE);
3412 emit_label (acfg, symbol);
3414 emit_bytes (acfg, buf, p - buf);
3418 * When running in aot-only mode, we can't create trampolines at runtime, so we create
3419 * a few, and save them in the AOT file. Normal trampolines embed their argument as a
3420 * literal inside the trampoline code, we can't do that here, so instead we embed an offset
3421 * which needs to be added to the trampoline address to get the address of the GOT slot
3422 * which contains the argument value.
3423 * The generated trampolines jump to the generic trampolines using another GOT slot, which
3424 * will be setup by the AOT loader to point to the generic trampoline code of the given
3428 emit_trampolines (MonoAotCompile *acfg)
3432 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3439 if (!acfg->aot_opts.full_aot)
3442 g_assert (acfg->image->assembly);
3444 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3445 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3446 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3448 * Emit the generic trampolines.
3450 * We could save some code by treating the generic trampolines as a wrapper
3451 * method, but that approach has its own complexities, so we choose the simpler
3454 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3455 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, TRUE);
3457 /* Emit trampoline code */
3459 sprintf (symbol, "generic_trampoline_%d", tramp_type);
3461 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3464 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3465 emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL);
3467 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3468 emit_named_code (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji);
3469 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3470 emit_named_code (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji);
3473 /* Emit the exception related code pieces */
3474 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3475 emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji);
3476 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3477 emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji);
3478 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3479 emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji);
3480 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3481 emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji);
3482 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3483 emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji);
3484 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3485 emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji);
3487 #if defined(__x86_64__) || defined(__arm__)
3488 for (i = 0; i < 128; ++i) {
3491 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3492 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3493 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3494 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3496 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3497 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3498 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3499 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3505 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3509 /* Reserve some entries at the end of the GOT for our use */
3510 acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
3512 sprintf (symbol, "trampolines");
3514 emit_section_change (acfg, ".text", 0);
3515 emit_global (acfg, symbol, TRUE);
3516 emit_alignment (acfg, 16);
3517 emit_label (acfg, symbol);
3519 for (i = 0; i < acfg->num_aot_trampolines; ++i) {
3520 offset = acfg->got_offset + (i * 2);
3523 * The trampolines created here are variations of the specific
3524 * trampolines created in mono_arch_create_specific_trampoline (). The
3526 * - the generic trampoline address is taken from a got slot.
3527 * - the offset of the got slot where the trampoline argument is stored
3528 * is embedded in the instruction stream, and the generic trampoline
3529 * can load the argument by loading the offset, adding it to the
3530 * address of the trampoline to get the address of the got slot, and
3531 * loading the argument from the there.
3533 #if defined(__x86_64__)
3534 /* This should be exactly 16 bytes long */
3535 /* It should work together with the generic trampoline code in tramp-amd64.c */
3536 /* call *<offset>(%rip) */
3537 emit_byte (acfg, '\x41');
3538 emit_byte (acfg, '\xff');
3539 emit_byte (acfg, '\x15');
3540 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
3541 /* This should be relative to the start of the trampoline */
3542 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
3543 emit_zero_bytes (acfg, 5);
3544 #elif defined(__arm__)
3548 /* Generate the trampoline code */
3549 /* This should be exactly 28 bytes long */
3552 ARM_PUSH (code, 0x5fff);
3553 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
3554 /* Load the value from the GOT */
3555 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
3557 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
3558 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
3560 g_assert (code - buf == 20);
3563 emit_bytes (acfg, buf, code - buf);
3564 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
3565 emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
3568 g_assert_not_reached ();
3573 /* Unbox trampolines */
3575 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3577 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3579 char call_target [256];
3581 method = mono_get_method (acfg->image, token, NULL);
3583 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3584 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
3587 sprintf (symbol, "unbox_trampoline_%d", i);
3589 emit_section_change (acfg, ".text", 0);
3590 emit_global (acfg, symbol, TRUE);
3591 emit_label (acfg, symbol);
3593 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
3595 #if defined(__x86_64__)
3600 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (cfg->orig_method), cfg->generic_sharing_context, NULL);
3602 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
3604 emit_bytes (acfg, buf, code - buf);
3606 emit_byte (acfg, '\xe9');
3607 emit_symbol_diff (acfg, call_target, ".", -4);
3609 #elif defined(__arm__)
3616 if (MONO_TYPE_ISSTRUCT (mono_method_signature (cfg->orig_method)->ret))
3619 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
3621 emit_bytes (acfg, buf, code - buf);
3622 /* jump to method */
3623 #if defined(USE_BIN_WRITER)
3625 g_assert_not_reached ();
3627 fprintf (acfg->fp, "\n\tb %s\n", call_target);
3631 g_assert_not_reached ();
3635 sprintf (symbol, "trampolines_info");
3637 emit_section_change (acfg, ".text", 0);
3638 emit_global (acfg, symbol, TRUE);
3639 emit_alignment (acfg, PAGESIZE);
3640 emit_label (acfg, symbol);
3642 emit_int32 (acfg, acfg->num_aot_trampolines);
3643 emit_int32 (acfg, acfg->got_offset);
3647 str_begins_with (const char *str1, const char *str2)
3649 int len = strlen (str2);
3650 return strncmp (str1, str2, len) == 0;
3654 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3656 gchar **args, **ptr;
3658 memset (opts, 0, sizeof (*opts));
3660 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3661 for (ptr = args; ptr && *ptr; ptr ++) {
3662 const char *arg = *ptr;
3664 if (str_begins_with (arg, "outfile=")) {
3665 opts->outfile = g_strdup (arg + strlen ("outfile="));
3666 } else if (str_begins_with (arg, "save-temps")) {
3667 opts->save_temps = TRUE;
3668 } else if (str_begins_with (arg, "keep-temps")) {
3669 opts->save_temps = TRUE;
3670 } else if (str_begins_with (arg, "write-symbols")) {
3671 opts->write_symbols = TRUE;
3672 } else if (str_begins_with (arg, "metadata-only")) {
3673 opts->metadata_only = TRUE;
3674 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3675 opts->bind_to_runtime_version = TRUE;
3676 } else if (str_begins_with (arg, "full")) {
3677 opts->full_aot = TRUE;
3679 * The no-dlsym option is only useful on the iphone, and even there,
3680 * do to other limitations of the dynamic linker, it doesn't seem to
3681 * work. So disable it for now so we don't have to support it.
3684 } else if (str_begins_with (arg, "no-dlsym")) {
3685 opts->no_dlsym = TRUE;
3687 } else if (str_begins_with (arg, "threads=")) {
3688 opts->nthreads = atoi (arg + strlen ("threads="));
3689 } else if (str_begins_with (arg, "static")) {
3690 opts->static_link = TRUE;
3691 opts->no_dlsym = TRUE;
3692 } else if (str_begins_with (arg, "asmonly")) {
3693 opts->asm_only = TRUE;
3695 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3704 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3706 MonoMethod *method = (MonoMethod*)key;
3707 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3708 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3709 MonoAotCompile *acfg = user_data;
3711 new_ji->image = ji->image;
3712 new_ji->token = ji->token;
3713 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3719 * AOT compile a given method.
3720 * This function might be called by multiple threads, so it must be thread-safe.
3723 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3726 MonoJumpInfo *patch_info;
3729 MonoMethod *wrapped;
3731 if (acfg->aot_opts.metadata_only)
3734 mono_acfg_lock (acfg);
3735 index = get_method_index (acfg, method);
3736 mono_acfg_unlock (acfg);
3738 /* fixme: maybe we can also precompile wrapper methods */
3739 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3740 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3741 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3742 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3746 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3749 wrapped = mono_marshal_method_from_wrapper (method);
3750 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3751 // FIXME: The wrapper should be generic too, but it is not
3754 InterlockedIncrement (&acfg->stats.mcount);
3756 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3758 * FIXME: Enabling this causes virtual-sync.exe to fail, since the trampoline
3759 * code can't determine that it needs to insert a sync wrapper in the AOT case.
3765 if (method->is_generic || method->klass->generic_container) {
3766 InterlockedIncrement (&acfg->stats.genericcount);
3771 if (acfg->aot_opts.full_aot)
3772 mono_use_imt = FALSE;
3775 * Since these methods are the only ones which are compiled with
3776 * AOT support, and they are not used by runtime startup/shutdown code,
3777 * the runtime will not see AOT methods during AOT compilation,so it
3778 * does not need to support them by creating a fake GOT etc.
3780 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3781 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3782 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3783 InterlockedIncrement (&acfg->stats.genericcount);
3786 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3787 /* Let the exception happen at runtime */
3791 if (cfg->disable_aot) {
3792 //printf ("Skip (other): %s\n", mono_method_full_name (method, TRUE));
3793 InterlockedIncrement (&acfg->stats.ocount);
3794 mono_destroy_compile (cfg);
3798 /* Nullify patches which need no aot processing */
3799 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3800 switch (patch_info->type) {
3801 case MONO_PATCH_INFO_LABEL:
3802 case MONO_PATCH_INFO_BB:
3803 patch_info->type = MONO_PATCH_INFO_NONE;
3810 /* Collect method->token associations from the cfg */
3811 mono_acfg_lock (acfg);
3812 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3813 mono_acfg_unlock (acfg);
3816 * Check for absolute addresses.
3819 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3820 switch (patch_info->type) {
3821 case MONO_PATCH_INFO_ABS:
3822 /* unable to handle this */
3823 //printf ("Skip (abs addr): %s %d\n", mono_method_full_name (method, TRUE), patch_info->type);
3832 InterlockedIncrement (&acfg->stats.abscount);
3833 mono_destroy_compile (cfg);
3838 * Check for wrapper methods we can't encode.
3841 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3842 if ((patch_info->type == MONO_PATCH_INFO_METHODCONST) || (patch_info->type == MONO_PATCH_INFO_METHOD)) {
3843 switch (patch_info->data.method->wrapper_type) {
3844 case MONO_WRAPPER_NONE:
3845 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3846 case MONO_WRAPPER_XDOMAIN_INVOKE:
3847 case MONO_WRAPPER_STFLD:
3848 case MONO_WRAPPER_LDFLD:
3849 case MONO_WRAPPER_LDFLDA:
3850 case MONO_WRAPPER_LDFLD_REMOTE:
3851 case MONO_WRAPPER_STFLD_REMOTE:
3852 case MONO_WRAPPER_STELEMREF:
3853 case MONO_WRAPPER_ISINST:
3854 case MONO_WRAPPER_PROXY_ISINST:
3855 case MONO_WRAPPER_ALLOC:
3856 case MONO_WRAPPER_REMOTING_INVOKE:
3857 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
3858 case MONO_WRAPPER_UNKNOWN:
3861 /* unable to handle this */
3862 //printf ("Skip (wrapper call): %s %d -> %s\n", mono_method_full_name (method, TRUE), patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
3866 } else if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH) {
3867 MonoJumpInfo *child = patch_info->data.rgctx_entry->data;
3869 if (child->type == MONO_PATCH_INFO_METHODCONST) {
3870 switch (child->data.method->wrapper_type) {
3871 case MONO_WRAPPER_NONE:
3872 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
3882 InterlockedIncrement (&acfg->stats.wrappercount);
3883 mono_destroy_compile (cfg);
3887 /* Lock for the rest of the code */
3888 mono_acfg_lock (acfg);
3891 * Check for methods/klasses we can't encode.
3894 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3895 switch (patch_info->type) {
3896 case MONO_PATCH_INFO_METHOD:
3897 case MONO_PATCH_INFO_METHODCONST:
3898 if (patch_info->data.method->wrapper_type)
3900 if (!patch_info->data.method->token) {
3901 /* The method is part of a constructed type like Int[,].Set (). */
3902 if (!g_hash_table_lookup (acfg->token_info_hash, patch_info->data.method))
3906 case MONO_PATCH_INFO_VTABLE:
3907 case MONO_PATCH_INFO_CLASS_INIT:
3908 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3909 case MONO_PATCH_INFO_CLASS:
3910 case MONO_PATCH_INFO_IID:
3911 case MONO_PATCH_INFO_ADJUSTED_IID:
3912 if (!patch_info->data.klass->type_token)
3913 if (!patch_info->data.klass->element_class->type_token && !(patch_info->data.klass->element_class->rank && patch_info->data.klass->element_class->element_class->type_token))
3922 acfg->stats.ocount++;
3923 mono_destroy_compile (cfg);
3924 mono_acfg_unlock (acfg);
3928 /* Adds generic instances referenced by this method */
3929 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3930 switch (patch_info->type) {
3931 case MONO_PATCH_INFO_METHOD: {
3932 MonoMethod *m = patch_info->data.method;
3933 if (m->is_inflated) {
3934 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3935 mono_method_is_generic_sharable_impl (m, FALSE)) &&
3936 !method_has_type_vars (m))
3937 add_extra_method (acfg, m);
3946 /* Determine whenever the method has GOT slots */
3947 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3948 switch (patch_info->type) {
3949 case MONO_PATCH_INFO_GOT_OFFSET:
3950 case MONO_PATCH_INFO_NONE:
3952 case MONO_PATCH_INFO_IMAGE:
3953 /* The assembly is stored in GOT slot 0 */
3954 if (patch_info->data.image != acfg->image)
3955 cfg->has_got_slots = TRUE;
3958 if (!is_plt_patch (patch_info))
3959 cfg->has_got_slots = TRUE;
3964 if (!cfg->has_got_slots)
3965 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3967 /* Make a copy of the patch info which is in the mempool */
3969 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3971 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3972 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3975 patches = new_patch_info;
3977 patches_end->next = new_patch_info;
3978 patches_end = new_patch_info;
3980 cfg->patch_info = patches;
3983 /* Free some fields used by cfg to conserve memory */
3984 mono_mempool_destroy (cfg->mempool);
3985 cfg->mempool = NULL;
3986 g_free (cfg->varinfo);
3987 cfg->varinfo = NULL;
3991 mono_regstate_free (cfg->rs);
3995 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
3997 while (index >= acfg->cfgs_size) {
3998 MonoCompile **new_cfgs;
4001 new_size = acfg->cfgs_size * 2;
4002 new_cfgs = g_new0 (MonoCompile*, new_size);
4003 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4004 g_free (acfg->cfgs);
4005 acfg->cfgs = new_cfgs;
4006 acfg->cfgs_size = new_size;
4008 acfg->cfgs [index] = cfg;
4010 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4012 if (cfg->orig_method->wrapper_type)
4013 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4015 mono_acfg_unlock (acfg);
4017 InterlockedIncrement (&acfg->stats.ccount);
4021 compile_thread_main (gpointer *user_data)
4023 MonoDomain *domain = user_data [0];
4024 MonoAotCompile *acfg = user_data [1];
4025 GPtrArray *methods = user_data [2];
4028 mono_thread_attach (domain);
4030 for (i = 0; i < methods->len; ++i)
4031 compile_method (acfg, g_ptr_array_index (methods, i));
4035 load_profile_files (MonoAotCompile *acfg)
4039 int file_index, res, method_index, i;
4046 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%s-%d", g_get_home_dir (), acfg->image->assembly_name, acfg->image->guid, file_index);
4048 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4053 infile = fopen (tmp, "r");
4056 printf ("Using profile data file '%s'\n", tmp);
4061 res = fscanf (infile, "%32s\n", ver);
4062 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
4063 printf ("Profile file has wrong version or invalid.\n");
4069 res = fscanf (infile, "%d\n", &token);
4073 method_index = mono_metadata_token_index (token) - 1;
4075 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
4076 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4081 /* Add missing methods */
4083 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4084 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4085 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4087 unordered = g_list_reverse (unordered);
4088 if (acfg->method_order)
4089 g_list_last (acfg->method_order)->next = unordered;
4091 acfg->method_order = unordered;
4097 * Collect all patches which have shared GOT entries and alloc entries for them. The
4098 * rest will get entries allocated during emit_code ().
4101 alloc_got_slots (MonoAotCompile *acfg)
4107 /* Slot 0 is reserved for the address of the current assembly */
4108 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
4109 ji->type = MONO_PATCH_INFO_IMAGE;
4110 ji->data.image = acfg->image;
4112 get_shared_got_offset (acfg, ji);
4114 for (l = acfg->method_order; l != NULL; l = l->next) {
4115 i = GPOINTER_TO_UINT (l->data);
4117 if (acfg->cfgs [i]) {
4118 MonoCompile *cfg = acfg->cfgs [i];
4120 for (ji = cfg->patch_info; ji; ji = ji->next) {
4121 if (is_shared_got_patch (ji))
4122 get_shared_got_offset (acfg, ji);
4129 emit_code (MonoAotCompile *acfg)
4135 sprintf (symbol, "methods");
4136 emit_section_change (acfg, ".text", 0);
4137 emit_global (acfg, symbol, TRUE);
4138 emit_alignment (acfg, 8);
4139 emit_label (acfg, symbol);
4141 for (l = acfg->method_order; l != NULL; l = l->next) {
4142 i = GPOINTER_TO_UINT (l->data);
4145 emit_method_code (acfg, acfg->cfgs [i]);
4148 sprintf (symbol, "methods_end");
4149 emit_section_change (acfg, ".text", 0);
4150 emit_global (acfg, symbol, FALSE);
4151 emit_alignment (acfg, 8);
4152 emit_label (acfg, symbol);
4154 sprintf (symbol, "method_offsets");
4155 emit_section_change (acfg, ".text", 1);
4156 emit_global (acfg, symbol, FALSE);
4157 emit_alignment (acfg, 8);
4158 emit_label (acfg, symbol);
4160 for (i = 0; i < acfg->nmethods; ++i) {
4161 if (acfg->cfgs [i]) {
4162 sprintf (symbol, ".Lm_%x", i);
4163 emit_symbol_diff (acfg, symbol, "methods", 0);
4165 emit_int32 (acfg, 0xffffffff);
4172 emit_info (MonoAotCompile *acfg)
4178 /* Emit method info */
4179 sprintf (symbol, "method_info");
4180 emit_section_change (acfg, ".text", 1);
4181 emit_global (acfg, symbol, FALSE);
4182 emit_alignment (acfg, 8);
4183 emit_label (acfg, symbol);
4185 /* To reduce size of generated assembly code */
4186 sprintf (symbol, "mi");
4187 emit_label (acfg, symbol);
4189 for (l = acfg->method_order; l != NULL; l = l->next) {
4190 i = GPOINTER_TO_UINT (l->data);
4193 emit_method_info (acfg, acfg->cfgs [i]);
4196 sprintf (symbol, "method_info_offsets");
4197 emit_section_change (acfg, ".text", 1);
4198 emit_global (acfg, symbol, FALSE);
4199 emit_alignment (acfg, 8);
4200 emit_label (acfg, symbol);
4202 for (i = 0; i < acfg->nmethods; ++i) {
4203 if (acfg->cfgs [i]) {
4204 sprintf (symbol, ".Lm_%x_p", i);
4205 emit_symbol_diff (acfg, symbol, "mi", 0);
4207 emit_int32 (acfg, 0);
4213 typedef struct HashEntry {
4214 guint32 key, value, index;
4215 struct HashEntry *next;
4219 * emit_extra_methods:
4221 * Emit methods which are not in the METHOD table, like wrappers.
4224 emit_extra_methods (MonoAotCompile *acfg)
4226 int i, table_size, buf_size;
4229 guint32 *info_offsets;
4232 HashEntry *entry, *new_entry;
4235 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4237 buf_size = acfg->extra_methods->len * 256 + 256;
4238 p = buf = g_malloc (buf_size);
4240 /* Encode method info */
4242 /* So offsets are > 0 */
4245 for (i = 0; i < acfg->extra_methods->len; ++i) {
4246 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4247 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4253 info_offsets [i] = p - buf;
4255 if (method->wrapper_type) {
4258 // FIXME: Optimize disk usage
4259 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
4260 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4261 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
4264 name = mono_method_full_name (cfg->orig_method, TRUE);
4267 encode_value (1, p, &p);
4268 strcpy ((char*)p, name);
4269 p += strlen (name ) + 1;
4272 encode_value (0, p, &p);
4273 encode_method_ref (acfg, method, p, &p);
4276 g_assert ((p - buf) < buf_size);
4279 g_assert ((p - buf) < buf_size);
4281 /* Emit method info */
4282 sprintf (symbol, "extra_method_info");
4283 emit_section_change (acfg, ".text", 1);
4284 emit_global (acfg, symbol, FALSE);
4285 emit_alignment (acfg, 8);
4286 emit_label (acfg, symbol);
4288 emit_bytes (acfg, buf, p - buf);
4293 * Construct a chained hash table for mapping indexes in extra_method_info to
4296 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4297 table = g_ptr_array_sized_new (table_size);
4298 for (i = 0; i < table_size; ++i)
4299 g_ptr_array_add (table, NULL);
4300 for (i = 0; i < acfg->extra_methods->len; ++i) {
4301 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4302 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4308 key = info_offsets [i];
4309 value = get_method_index (acfg, method);
4311 if (method->wrapper_type) {
4312 hash = g_str_hash (method->name) % table_size;
4315 hash = 0 % table_size;
4318 /* FIXME: Allocate from the mempool */
4319 new_entry = g_new0 (HashEntry, 1);
4320 new_entry->key = key;
4321 new_entry->value = value;
4323 entry = g_ptr_array_index (table, hash);
4324 if (entry == NULL) {
4325 new_entry->index = hash;
4326 g_ptr_array_index (table, hash) = new_entry;
4329 entry = entry->next;
4331 entry->next = new_entry;
4332 new_entry->index = table->len;
4333 g_ptr_array_add (table, new_entry);
4337 /* Emit the table */
4338 sprintf (symbol, "extra_method_table");
4339 emit_section_change (acfg, ".text", 0);
4340 emit_global (acfg, symbol, FALSE);
4341 emit_alignment (acfg, 8);
4342 emit_label (acfg, symbol);
4344 g_assert (table_size < 65000);
4345 emit_int32 (acfg, table_size);
4346 g_assert (table->len < 65000);
4347 for (i = 0; i < table->len; ++i) {
4348 HashEntry *entry = g_ptr_array_index (table, i);
4350 if (entry == NULL) {
4351 emit_int32 (acfg, 0);
4352 emit_int32 (acfg, 0);
4353 emit_int32 (acfg, 0);
4355 g_assert (entry->key > 0);
4356 emit_int32 (acfg, entry->key);
4357 emit_int32 (acfg, entry->value);
4359 emit_int32 (acfg, entry->next->index);
4361 emit_int32 (acfg, 0);
4366 * Emit a table reverse mapping method indexes to their index in extra_method_info.
4367 * This is used by mono_aot_find_jit_info ().
4369 sprintf (symbol, "extra_method_info_offsets");
4370 emit_section_change (acfg, ".text", 0);
4371 emit_global (acfg, symbol, FALSE);
4372 emit_alignment (acfg, 8);
4373 emit_label (acfg, symbol);
4375 emit_int32 (acfg, acfg->extra_methods->len);
4376 for (i = 0; i < acfg->extra_methods->len; ++i) {
4377 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4379 emit_int32 (acfg, get_method_index (acfg, method));
4380 emit_int32 (acfg, info_offsets [i]);
4385 emit_method_order (MonoAotCompile *acfg)
4391 sprintf (symbol, "method_order");
4392 emit_section_change (acfg, ".text", 1);
4393 emit_global (acfg, symbol, FALSE);
4394 emit_alignment (acfg, 8);
4395 emit_label (acfg, symbol);
4397 /* First emit an index table */
4400 for (l = acfg->method_order; l != NULL; l = l->next) {
4401 i = GPOINTER_TO_UINT (l->data);
4403 if (acfg->cfgs [i]) {
4404 if ((index % 1024) == 0) {
4405 emit_int32 (acfg, i);
4413 emit_int32 (acfg, 0xffffff);
4415 /* Then emit the whole method order */
4416 for (l = acfg->method_order; l != NULL; l = l->next) {
4417 i = GPOINTER_TO_UINT (l->data);
4419 if (acfg->cfgs [i]) {
4420 emit_int32 (acfg, i);
4425 sprintf (symbol, "method_order_end");
4426 emit_section_change (acfg, ".text", 1);
4427 emit_global (acfg, symbol, FALSE);
4428 emit_label (acfg, symbol);
4432 emit_exception_info (MonoAotCompile *acfg)
4437 sprintf (symbol, "ex_info");
4438 emit_section_change (acfg, ".text", 1);
4439 emit_global (acfg, symbol, FALSE);
4440 emit_alignment (acfg, 8);
4441 emit_label (acfg, symbol);
4443 /* To reduce size of generated assembly */
4444 sprintf (symbol, "ex");
4445 emit_label (acfg, symbol);
4447 for (i = 0; i < acfg->nmethods; ++i) {
4449 emit_exception_debug_info (acfg, acfg->cfgs [i]);
4452 sprintf (symbol, "ex_info_offsets");
4453 emit_section_change (acfg, ".text", 1);
4454 emit_global (acfg, symbol, FALSE);
4455 emit_alignment (acfg, 8);
4456 emit_label (acfg, symbol);
4458 for (i = 0; i < acfg->nmethods; ++i) {
4459 if (acfg->cfgs [i]) {
4460 sprintf (symbol, ".Le_%x_p", i);
4461 emit_symbol_diff (acfg, symbol, "ex", 0);
4463 emit_int32 (acfg, 0);
4470 emit_class_info (MonoAotCompile *acfg)
4475 sprintf (symbol, "class_info");
4476 emit_section_change (acfg, ".text", 1);
4477 emit_global (acfg, symbol, FALSE);
4478 emit_alignment (acfg, 8);
4479 emit_label (acfg, symbol);
4481 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4482 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4484 sprintf (symbol, "class_info_offsets");
4485 emit_section_change (acfg, ".text", 1);
4486 emit_global (acfg, symbol, FALSE);
4487 emit_alignment (acfg, 8);
4488 emit_label (acfg, symbol);
4490 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4491 sprintf (symbol, ".LK_I_%x", i);
4492 emit_symbol_diff (acfg, symbol, "class_info", 0);
4497 typedef struct ClassNameTableEntry {
4498 guint32 token, index;
4499 struct ClassNameTableEntry *next;
4500 } ClassNameTableEntry;
4503 emit_class_name_table (MonoAotCompile *acfg)
4506 guint32 token, hash;
4511 ClassNameTableEntry *entry, *new_entry;
4514 * Construct a chained hash table for mapping class names to typedef tokens.
4516 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4517 table = g_ptr_array_sized_new (table_size);
4518 for (i = 0; i < table_size; ++i)
4519 g_ptr_array_add (table, NULL);
4520 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4521 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4522 klass = mono_class_get (acfg->image, token);
4523 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4524 hash = g_str_hash (full_name) % table_size;
4527 /* FIXME: Allocate from the mempool */
4528 new_entry = g_new0 (ClassNameTableEntry, 1);
4529 new_entry->token = token;
4531 entry = g_ptr_array_index (table, hash);
4532 if (entry == NULL) {
4533 new_entry->index = hash;
4534 g_ptr_array_index (table, hash) = new_entry;
4537 entry = entry->next;
4539 entry->next = new_entry;
4540 new_entry->index = table->len;
4541 g_ptr_array_add (table, new_entry);
4545 /* Emit the table */
4546 sprintf (symbol, "class_name_table");
4547 emit_section_change (acfg, ".text", 0);
4548 emit_global (acfg, symbol, FALSE);
4549 emit_alignment (acfg, 8);
4550 emit_label (acfg, symbol);
4552 /* FIXME: Optimize memory usage */
4553 g_assert (table_size < 65000);
4554 emit_int16 (acfg, table_size);
4555 g_assert (table->len < 65000);
4556 for (i = 0; i < table->len; ++i) {
4557 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4559 if (entry == NULL) {
4560 emit_int16 (acfg, 0);
4561 emit_int16 (acfg, 0);
4563 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4565 emit_int16 (acfg, entry->next->index);
4567 emit_int16 (acfg, 0);
4573 emit_image_table (MonoAotCompile *acfg)
4579 * The image table is small but referenced in a lot of places.
4580 * So we emit it at once, and reference its elements by an index.
4583 sprintf (symbol, "mono_image_table");
4584 emit_section_change (acfg, ".text", 1);
4585 emit_global (acfg, symbol, FALSE);
4586 emit_alignment (acfg, 8);
4587 emit_label (acfg, symbol);
4589 emit_int32 (acfg, acfg->image_table->len);
4590 for (i = 0; i < acfg->image_table->len; i++) {
4591 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4592 MonoAssemblyName *aname = &image->assembly->aname;
4594 /* FIXME: Support multi-module assemblies */
4595 g_assert (image->assembly->image == image);
4597 emit_string (acfg, image->assembly_name);
4598 emit_string (acfg, image->guid);
4599 emit_string (acfg, aname->culture ? aname->culture : "");
4600 emit_string (acfg, (const char*)aname->public_key_token);
4602 emit_alignment (acfg, 8);
4603 emit_int32 (acfg, aname->flags);
4604 emit_int32 (acfg, aname->major);
4605 emit_int32 (acfg, aname->minor);
4606 emit_int32 (acfg, aname->build);
4607 emit_int32 (acfg, aname->revision);
4612 emit_got_info (MonoAotCompile *acfg)
4617 guint32 *got_info_offsets;
4621 * - optimize offsets table.
4622 * - reduce number of exported symbols.
4623 * - emit info for a klass only once.
4624 * - determine when a method uses a GOT slot which is guaranteed to be already
4626 * - clean up and document the code.
4627 * - use String.Empty in class libs.
4630 /* Encode info required to decode shared GOT entries */
4631 buf_size = acfg->shared_patches->len * 64;
4632 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4633 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
4634 for (i = 0; i < acfg->shared_patches->len; ++i) {
4635 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
4637 /* No need to encode the patch type */
4638 got_info_offsets [i] = p - buf;
4639 encode_patch (acfg, ji, p, &p);
4642 g_assert (p - buf <= buf_size);
4644 acfg->stats.got_info_size = p - buf;
4646 /* Emit got_info table */
4647 sprintf (symbol, "got_info");
4648 emit_section_change (acfg, ".text", 1);
4649 emit_global (acfg, symbol, FALSE);
4650 emit_alignment (acfg, 8);
4651 emit_label (acfg, symbol);
4653 emit_bytes (acfg, buf, p - buf);
4655 /* Emit got_info_offsets table */
4656 sprintf (symbol, "got_info_offsets");
4657 emit_section_change (acfg, ".text", 1);
4658 emit_global (acfg, symbol, FALSE);
4659 emit_alignment (acfg, 8);
4660 emit_label (acfg, symbol);
4662 for (i = 0; i < acfg->shared_patches->len; ++i)
4663 emit_int32 (acfg, got_info_offsets [i]);
4665 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
4669 emit_got (MonoAotCompile *acfg)
4673 /* Don't make GOT global so accesses to it don't need relocations */
4674 sprintf (symbol, "got");
4675 emit_section_change (acfg, ".bss", 1);
4676 emit_alignment (acfg, 8);
4677 emit_label (acfg, symbol);
4678 if ((acfg->got_offset + acfg->num_trampoline_got_entries) > 0)
4679 emit_zero_bytes (acfg, (int)((acfg->got_offset + acfg->num_trampoline_got_entries) * sizeof (gpointer)));
4681 sprintf (symbol, "got_addr");
4682 emit_section_change (acfg, ".data", 1);
4683 emit_global (acfg, symbol, FALSE);
4684 emit_alignment (acfg, 8);
4685 emit_label (acfg, symbol);
4686 emit_pointer (acfg, "got");
4688 sprintf (symbol, "got_size");
4689 emit_section_change (acfg, ".data", 1);
4690 emit_global (acfg, symbol, FALSE);
4691 emit_alignment (acfg, 8);
4692 emit_label (acfg, symbol);
4693 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4697 emit_globals (MonoAotCompile *acfg)
4702 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4704 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4706 opts_str = g_strdup_printf ("%d", acfg->opts);
4707 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4710 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4712 if (acfg->aot_opts.bind_to_runtime_version) {
4713 build_info = mono_get_runtime_build_info ();
4714 emit_string_symbol (acfg, "mono_runtime_version", build_info);
4715 g_free (build_info);
4717 emit_string_symbol (acfg, "mono_runtime_version", "");
4721 * Some platforms like the iphone have no working dlsym (). To work around this,
4722 * we create an ELF ctor function which will be invoked by dlopen, and which
4723 * will call a function in the AOT loader to register the symbols used by the
4725 * When static linking, we emit a global which will point to the symbol table.
4727 if (acfg->aot_opts.no_dlsym) {
4731 if (acfg->aot_opts.static_link)
4732 /* Emit a string holding the assembly name */
4733 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4735 /* Emit the names */
4736 for (i = 0; i < acfg->globals->len; ++i) {
4737 char *name = g_ptr_array_index (acfg->globals, i);
4739 sprintf (symbol, "name_%d", i);
4740 emit_section_change (acfg, ".text", 1);
4741 emit_label (acfg, symbol);
4742 emit_string (acfg, name);
4745 /* Emit the globals table */
4746 sprintf (symbol, "globals");
4747 emit_section_change (acfg, ".data", 0);
4748 /* This is not a global, since it is accessed by the init function */
4749 emit_alignment (acfg, 8);
4750 emit_label (acfg, symbol);
4752 for (i = 0; i < acfg->globals->len; ++i) {
4753 char *name = g_ptr_array_index (acfg->globals, i);
4755 sprintf (symbol, "name_%d", i);
4756 emit_pointer (acfg, symbol);
4758 sprintf (symbol, "%s", name);
4759 emit_pointer (acfg, symbol);
4761 /* Null terminate the table */
4762 emit_pointer (acfg, NULL);
4763 emit_pointer (acfg, NULL);
4765 if (acfg->aot_opts.static_link) {
4769 * Emit a global symbol which can be passed by an embedding app to
4770 * mono_aot_register_module ().
4772 #if defined(__MACH__)
4773 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4775 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4778 /* Get rid of characters which cannot occur in symbols */
4780 for (p = symbol; *p; ++p) {
4781 if (!(isalnum (*p) || *p == '_'))
4784 acfg->static_linking_symbol = g_strdup (symbol);
4785 emit_global_inner (acfg, symbol, FALSE);
4786 emit_alignment (acfg, 8);
4787 emit_label (acfg, symbol);
4788 emit_pointer (acfg, "globals");
4790 sprintf (symbol, "init_%s", acfg->image->assembly->aname.name);
4791 emit_section_change (acfg, ".text", 1);
4792 emit_alignment (acfg, 8);
4793 emit_label (acfg, symbol);
4794 #ifdef USE_BIN_WRITER
4795 g_assert_not_reached ();
4798 fprintf (acfg->fp, "leaq globals(%%rip), %%rdi\n");
4799 fprintf (acfg->fp, "call mono_aot_register_globals@PLT\n");
4800 fprintf (acfg->fp, "ret\n");
4801 fprintf (acfg->fp, ".section .ctors,\"aw\",@progbits\n");
4802 emit_alignment (acfg, 8);
4803 emit_pointer (acfg, symbol);
4804 #elif defined(__arm__) && defined(__MACH__)
4806 fprintf (acfg->fp, ".text\n");
4807 fprintf (acfg->fp, ".align 3\n");
4809 fprintf (acfg->fp, "ldr r0, .L5\n");
4810 fprintf (acfg->fp, ".LPIC0:\n");
4811 fprintf (acfg->fp, "add r0, pc, r0\n");
4812 fprintf (acfg->fp, "ldr r0, [r0]\n");
4813 fprintf (acfg->fp, "b _mono_aot_register_globals@PLT\n");
4814 fprintf (acfg->fp, ".align 2\n");
4816 fprintf (acfg->fp, ".L5:\n");
4817 fprintf (acfg->fp, ".long globals_ptr-(.LPIC0+8)\n");
4819 fprintf (acfg->fp, ".data\n");
4820 fprintf (acfg->fp, ".align 2\n");
4821 fprintf (acfg->fp, "globals_ptr:\n");
4822 fprintf (acfg->fp, ".long globals\n");
4824 fprintf (acfg->fp, ".mod_init_func\n");
4825 fprintf (acfg->fp, ".align 2\n");
4826 fprintf (acfg->fp, ".long %s@target1\n", symbol);
4828 #elif defined(__arm__)
4830 * Taken from gcc generated code for:
4832 * void foo () { bar (&i); }
4833 * gcc --shared -fPIC -O2
4835 fprintf (acfg->fp, "ldr r3, .L5\n");
4836 fprintf (acfg->fp, "ldr r0, .L5+4\n");
4837 fprintf (acfg->fp, ".LPIC0:\n");
4838 fprintf (acfg->fp, "add r3, pc, r3\n");
4839 fprintf (acfg->fp, "add r0, r3, r0\n");
4840 fprintf (acfg->fp, "b mono_aot_register_globals(PLT)\n");
4842 fprintf (acfg->fp, ".L5:\n");
4843 fprintf (acfg->fp, ".word _GLOBAL_OFFSET_TABLE_-(.LPIC0+8)\n");
4844 fprintf (acfg->fp, ".word globals(GOTOFF)\n");
4846 fprintf (acfg->fp, ".section .init_array,\"aw\",%%init_array\n");
4847 fprintf (acfg->fp, ".align 2\n");
4848 fprintf (acfg->fp, ".word %s(target1)\n", symbol);
4850 g_assert_not_reached ();
4858 acfg_free (MonoAotCompile *acfg)
4862 for (i = 0; i < acfg->nmethods; ++i)
4864 g_free (acfg->cfgs [i]);
4865 g_free (acfg->cfgs);
4866 g_free (acfg->static_linking_symbol);
4867 g_ptr_array_free (acfg->methods, TRUE);
4868 g_ptr_array_free (acfg->shared_patches, TRUE);
4869 g_ptr_array_free (acfg->image_table, TRUE);
4870 g_ptr_array_free (acfg->globals, TRUE);
4871 g_hash_table_destroy (acfg->method_indexes);
4872 g_hash_table_destroy (acfg->plt_offset_to_patch);
4873 g_hash_table_destroy (acfg->patch_to_plt_offset);
4874 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
4875 g_hash_table_destroy (acfg->method_to_cfg);
4876 g_hash_table_destroy (acfg->token_info_hash);
4877 g_hash_table_destroy (acfg->image_hash);
4878 mono_mempool_destroy (acfg->mempool);
4883 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4885 MonoImage *image = ass->image;
4887 int i, res, methods_len;
4888 MonoAotCompile *acfg;
4892 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4894 acfg = g_new0 (MonoAotCompile, 1);
4895 acfg->methods = g_ptr_array_new ();
4896 acfg->method_indexes = g_hash_table_new (NULL, NULL);
4897 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4898 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4899 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4900 acfg->shared_patches = g_ptr_array_new ();
4901 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4902 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4903 acfg->image_hash = g_hash_table_new (NULL, NULL);
4904 acfg->image_table = g_ptr_array_new ();
4905 acfg->globals = g_ptr_array_new ();
4906 acfg->image = image;
4908 acfg->mempool = mono_mempool_new ();
4909 acfg->extra_methods = g_ptr_array_new ();
4910 InitializeCriticalSection (&acfg->mutex);
4912 mono_aot_parse_options (aot_options, &acfg->aot_opts);
4914 load_profile_files (acfg);
4918 acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 10240 : 0;
4920 acfg->method_index = 1;
4922 /* Collect methods */
4923 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4925 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4927 method = mono_get_method (acfg->image, token, NULL);
4929 /* Load all methods eagerly to skip the slower lazy loading code */
4930 mono_class_setup_methods (method->klass);
4932 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4933 /* Compile the wrapper instead */
4934 /* We do this here instead of add_wrappers () because it is easy to do it here */
4935 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4939 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4940 add_method_with_index (acfg, method, i);
4941 acfg->method_index ++;
4944 add_generic_instances (acfg);
4946 if (acfg->aot_opts.full_aot)
4947 add_wrappers (acfg);
4949 acfg->cfgs_size = acfg->methods->len + 32;
4950 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
4952 /* PLT offset 0 is reserved for the PLT trampoline */
4953 acfg->plt_offset = 1;
4955 /* Compile methods */
4958 if (acfg->aot_opts.nthreads > 0) {
4963 gpointer *user_data;
4964 MonoMethod **methods;
4966 methods_len = acfg->methods->len;
4968 len = acfg->methods->len / acfg->aot_opts.nthreads;
4971 * Partition the list of methods into fragments, and hand it to threads to
4974 threads = g_ptr_array_new ();
4975 /* Make a copy since acfg->methods is modified by compile_method () */
4976 methods = g_new0 (MonoMethod*, methods_len);
4977 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
4978 for (i = 0; i < methods_len; ++i)
4979 methods [i] = g_ptr_array_index (acfg->methods, i);
4981 while (i < methods_len) {
4982 frag = g_ptr_array_new ();
4983 for (j = 0; j < len; ++j) {
4984 if (i < methods_len) {
4985 g_ptr_array_add (frag, methods [i]);
4990 user_data = g_new0 (gpointer, 3);
4991 user_data [0] = mono_domain_get ();
4992 user_data [1] = acfg;
4993 user_data [2] = frag;
4995 handle = CreateThread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
4996 g_ptr_array_add (threads, handle);
5000 for (i = 0; i < threads->len; ++i) {
5001 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5007 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5008 for (i = methods_len; i < acfg->methods->len; ++i) {
5009 /* This can new methods to acfg->methods */
5010 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5015 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
5019 alloc_got_slots (acfg);
5025 emit_extra_methods (acfg);
5027 emit_method_order (acfg);
5029 emit_trampolines (acfg);
5031 emit_class_name_table (acfg);
5033 emit_got_info (acfg);
5035 emit_exception_info (acfg);
5037 emit_class_info (acfg);
5041 emit_image_table (acfg);
5045 emit_globals (acfg);
5047 sprintf (symbol, "mem_end");
5048 emit_section_change (acfg, ".text", 1);
5049 emit_global (acfg, symbol, FALSE);
5050 emit_alignment (acfg, 8);
5051 emit_label (acfg, symbol);
5055 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
5057 printf ("Code: %d Info: %d Ex Info: %d Class Info: %d PLT: %d GOT Info: %d GOT Info Offsets: %d GOT: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, acfg->stats.got_info_offsets_size, (int)(acfg->got_offset * sizeof (gpointer)));
5060 res = emit_writeout (acfg);
5066 acfg->stats.link_time = TV_ELAPSED (atv, btv);
5068 printf ("Compiled %d out of %d methods (%d%%)\n", acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100);
5069 if (acfg->stats.genericcount)
5070 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
5071 if (acfg->stats.abscount)
5072 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
5073 if (acfg->stats.wrappercount)
5074 printf ("%d methods contain wrapper references (%d%%)\n", acfg->stats.wrappercount, acfg->stats.mcount ? (acfg->stats.wrappercount * 100) / acfg->stats.mcount : 100);
5075 if (acfg->stats.lmfcount)
5076 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
5077 if (acfg->stats.ocount)
5078 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
5079 printf ("Methods without GOT slots: %d (%d%%)\n", acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100);
5080 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
5081 printf ("JIT time: %d ms, Generation time: %d ms, Assembly+Link time: %d ms.\n", acfg->stats.jit_time / 1000, acfg->stats.gen_time / 1000, acfg->stats.link_time / 1000);
5083 printf ("GOT slot distribution:\n");
5084 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
5085 if (acfg->stats.got_slot_types [i])
5086 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
5098 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)