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 * - during loading, collect the names into a hashtable to avoid linear
15 * - aot IMT tables, so we don't have two kinds of aot code.
16 * - optimize the trampolines, generate more code in the arch files.
17 * - make things more consistent with how elf works, for example, use ELF
22 #include <sys/types.h>
28 #ifndef PLATFORM_WIN32
37 #include <limits.h> /* for PAGESIZE */
42 #include <mono/metadata/tabledefs.h>
43 #include <mono/metadata/class.h>
44 #include <mono/metadata/object.h>
45 #include <mono/metadata/tokentype.h>
46 #include <mono/metadata/appdomain.h>
47 #include <mono/metadata/debug-helpers.h>
48 #include <mono/metadata/assembly.h>
49 #include <mono/metadata/metadata-internals.h>
50 #include <mono/metadata/marshal.h>
51 #include <mono/metadata/gc-internal.h>
52 #include <mono/metadata/method-builder.h>
53 #include <mono/utils/mono-logger.h>
54 #include "mono/utils/mono-compiler.h"
62 #define SHARED_EXT ".dll"
63 #elif defined(__ppc__) && defined(__MACH__)
64 #define SHARED_EXT ".dylib"
66 #define SHARED_EXT ".so"
69 #if defined(sparc) || defined(__ppc__)
70 #define AS_STRING_DIRECTIVE ".asciz"
73 #define AS_STRING_DIRECTIVE ".string"
76 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
77 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
79 typedef struct MonoAotOptions {
82 gboolean write_symbols;
83 gboolean metadata_only;
84 gboolean bind_to_runtime_version;
89 typedef struct MonoAotStats {
90 int ccount, mcount, lmfcount, abscount, wrappercount, gcount, ocount, genericcount;
91 int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
92 int methods_without_got_slots, direct_calls, all_calls;
94 int got_slot_types [MONO_PATCH_INFO_NONE];
97 /*#define USE_ELF_WRITER 1*/
99 #if defined(USE_ELF_WRITER)
100 #define USE_BIN_WRITER 1
103 #ifdef USE_BIN_WRITER
105 typedef struct _BinSymbol BinSymbol;
106 typedef struct _BinReloc BinReloc;
107 typedef struct _BinSection BinSection;
121 typedef struct MonoAotCompile {
124 GHashTable *method_indexes;
126 GHashTable *patch_to_plt_offset;
127 GHashTable **patch_to_plt_offset_wrapper;
128 GHashTable *plt_offset_to_patch;
129 GHashTable *patch_to_shared_got_offset;
130 GPtrArray *shared_patches;
131 GHashTable *image_hash;
132 GHashTable *method_to_cfg;
133 GHashTable *token_info_hash;
134 GPtrArray *image_table;
137 /* Number of trampolines emitted into the AOT file */
138 guint32 num_aot_trampolines;
139 guint32 got_offset, plt_offset;
140 /* Number of GOT entries reserved for trampolines */
141 guint32 num_trampoline_got_entries;
142 guint32 *method_got_offsets;
143 MonoAotOptions aot_opts;
146 MonoMemPool *mempool;
149 #ifdef USE_BIN_WRITER
151 BinSection *sections;
152 BinSection *cur_section;
153 BinReloc *relocations;
159 int mode; /* emit mode */
160 int col_count; /* bytes emitted per .byte line */
164 #ifdef HAVE_ARRAY_ELEM_INIT
165 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
166 #define MSGSTRFIELD1(line) str##line
167 static const struct msgstr_t {
168 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
169 #include "patch-info.h"
172 #define PATCH_INFO(a,b) b,
173 #include "patch-info.h"
176 static const gint16 opidx [] = {
177 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
178 #include "patch-info.h"
183 get_patch_name (int info)
185 return (const char*)&opstr + opidx [info];
189 #define PATCH_INFO(a,b) b,
190 static const char* const
191 patch_types [MONO_PATCH_INFO_NUM + 1] = {
192 #include "patch-info.h"
197 get_patch_name (int info)
199 return patch_types [info];
205 emit_global (MonoAotCompile *acfg, const char *name, gboolean func);
208 is_got_patch (MonoJumpInfoType patch_type)
213 static G_GNUC_UNUSED int
214 ilog2(register int value)
217 while (value & ~0xf) count += 4, value >>= 4;
218 while (value) count++, value >>= 1;
222 #ifdef USE_BIN_WRITER
224 typedef struct _BinLabel BinLabel;
235 BinSection *val2_section;
247 gboolean is_function;
265 emit_start (MonoAotCompile *acfg)
267 acfg->labels = g_hash_table_new (g_str_hash, g_str_equal);
271 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
275 if (acfg->cur_section && acfg->cur_section->subsection == subsection_index
276 && strcmp (acfg->cur_section->name, section_name) == 0)
278 for (section = acfg->sections; section; section = section->next) {
279 if (section->subsection == subsection_index && strcmp (section->name, section_name) == 0) {
280 acfg->cur_section = section;
285 section = g_new0 (BinSection, 1);
286 section->name = g_strdup (section_name);
287 section->subsection = subsection_index;
288 section->next = acfg->sections;
289 acfg->sections = section;
290 acfg->cur_section = section;
295 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
297 BinSymbol *symbol = g_new0 (BinSymbol, 1);
298 symbol->name = g_strdup (name);
299 symbol->is_function = func;
300 symbol->is_global = TRUE;
301 symbol->section = acfg->cur_section;
302 /* FIXME: we align after this call... */
303 symbol->offset = symbol->section->cur_offset;
304 symbol->next = acfg->symbols;
305 acfg->symbols = symbol;
309 emit_label (MonoAotCompile *acfg, const char *name)
311 BinLabel *label = g_new0 (BinLabel, 1);
312 label->name = g_strdup (name);
313 label->section = acfg->cur_section;
314 label->offset = acfg->cur_section->cur_offset;
315 g_hash_table_insert (acfg->labels, label->name, label);
319 emit_ensure_buffer (BinSection *section, int size)
321 int new_offset = section->cur_offset + size;
322 if (new_offset >= section->data_len) {
323 int new_size = section->data_len? section->data_len * 2: 256;
325 while (new_size <= new_offset)
327 data = g_malloc0 (new_size);
328 memcpy (data, section->data, section->data_len);
329 g_free (section->data);
330 section->data = data;
331 section->data_len = new_size;
336 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
338 emit_ensure_buffer (acfg->cur_section, size);
339 memcpy (acfg->cur_section->data + acfg->cur_section->cur_offset, buf, size);
340 acfg->cur_section->cur_offset += size;
344 emit_string (MonoAotCompile *acfg, const char *value)
346 int size = strlen (value) + 1;
347 emit_bytes (acfg, (const guint8*)value, size);
351 emit_line (MonoAotCompile *acfg)
353 /* Nothing to do in binary writer */
357 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
359 emit_section_change (acfg, ".text", 1);
360 emit_global (acfg, name, FALSE);
361 emit_label (acfg, name);
362 emit_string (acfg, value);
366 emit_alignment (MonoAotCompile *acfg, int size)
368 int offset = acfg->cur_section->cur_offset;
370 offset += (size - 1);
371 offset &= ~(size - 1);
372 add = offset - acfg->cur_section->cur_offset;
374 emit_ensure_buffer (acfg->cur_section, add);
375 acfg->cur_section->cur_offset += add;
380 emit_pointer (MonoAotCompile *acfg, const char *target)
386 g_assert_not_reached ();
387 emit_alignment (acfg, sizeof (gpointer));
388 reloc = g_new0 (BinReloc, 1);
389 reloc->val1 = g_strdup (target);
390 reloc->section = acfg->cur_section;
391 reloc->section_offset = acfg->cur_section->cur_offset;
392 reloc->next = acfg->relocations;
393 acfg->relocations = reloc;
394 if (strcmp (reloc->section->name, ".data") == 0) {
396 g_print ("reloc: %s at %d\n", target, acfg->cur_section->cur_offset);
398 acfg->cur_section->cur_offset += sizeof (gpointer);
402 emit_int16 (MonoAotCompile *acfg, int value)
405 emit_ensure_buffer (acfg->cur_section, 2);
406 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
407 acfg->cur_section->cur_offset += 2;
408 /* FIXME: little endian */
410 data [1] = value >> 8;
414 emit_int32 (MonoAotCompile *acfg, int value)
417 emit_ensure_buffer (acfg->cur_section, 4);
418 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
419 acfg->cur_section->cur_offset += 4;
420 /* FIXME: little endian */
422 data [1] = value >> 8;
423 data [2] = value >> 16;
424 data [3] = value >> 24;
428 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
431 reloc = g_new0 (BinReloc, 1);
432 reloc->val1 = g_strdup (end);
433 if (strcmp (start, ".") == 0) {
434 reloc->val2_section = acfg->cur_section;
435 reloc->val2_offset = acfg->cur_section->cur_offset;
437 reloc->val2 = g_strdup (start);
439 reloc->offset = offset;
440 reloc->section = acfg->cur_section;
441 reloc->section_offset = acfg->cur_section->cur_offset;
442 reloc->next = acfg->relocations;
443 acfg->relocations = reloc;
444 acfg->cur_section->cur_offset += 4;
445 /*if (strcmp (reloc->section->name, ".data") == 0) {
447 g_print ("reloc: %s - %s + %d at %d\n", end, start, offset, acfg->cur_section->cur_offset - 4);
452 emit_zero_bytes (MonoAotCompile *acfg, int num)
454 emit_ensure_buffer (acfg->cur_section, num);
455 acfg->cur_section->cur_offset += num;
458 #ifdef USE_ELF_WRITER
493 DYN_RELCOUNT = 0x6ffffffa
496 static const char* section_names [] = {
512 static const guint8 section_type [] = {
517 static const guint8 section_link [] = {
518 0, 2, 3, 0, 2, 0, 3, 0, 0, 0, 0, 12, 0
521 static const guint8 section_esize [] = {
522 0, 4, 16, 0, 8, 0, 8, 4, 0, 0, 0, 16, 0
525 static const guint8 section_flags [] = {
526 0, 2, 2, 2, 2, 6, 3, 3, 3, 3, 0, 0, 0
529 static const guint16 section_align [] = {
530 0, 4, 4, 1, 4, 4096, 4, 4, 8, 8, 1, 4, 1
550 struct ElfSectHeader {
563 #if SIZEOF_VOID_P == 4
565 struct ElfProgHeader {
597 struct ElfProgHeader {
641 str_table_add (ElfStrTable *table, const char* value)
645 table->data = g_string_new_len ("", 1);
646 table->hash = g_hash_table_new (g_str_hash, g_str_equal);
648 idx = GPOINTER_TO_UINT (g_hash_table_lookup (table->hash, value));
651 idx = table->data->len;
652 g_string_append (table->data, value);
653 g_string_append_c (table->data, 0);
654 g_hash_table_insert (table->hash, (void*)value, GUINT_TO_POINTER (idx));
659 append_subsection (MonoAotCompile *acfg, struct ElfSectHeader *sheaders, BinSection *sect, BinSection *add)
661 int offset = sect->cur_offset;
662 /*offset += (sheaders [sect->shidx].sh_addralign - 1);
663 offset &= ~(sheaders [sect->shidx].sh_addralign - 1);*/
666 emit_ensure_buffer (sect, offset);
667 g_print ("section %s aligned to %d from %d\n", sect->name, offset, sect->cur_offset);
668 sect->cur_offset = offset;
670 emit_ensure_buffer (sect, add->cur_offset);
671 memcpy (sect->data + sect->cur_offset, add->data, add->cur_offset);
673 sect->cur_offset += add->cur_offset;
674 add->cur_offset = offset; /* it becomes the offset in the parent section */
675 g_print ("subsection %d of %s added at offset %d (align: %d)\n", add->subsection, sect->name, add->cur_offset, sheaders [sect->shidx].sh_addralign);
680 /* merge the subsections */
682 collect_sections (MonoAotCompile *acfg, struct ElfSectHeader *sheaders, BinSection **out, int num)
684 int i, j, maxs, num_sections;
689 for (sect = acfg->sections; sect; sect = sect->next) {
690 if (sect->subsection == 0) {
691 out [num_sections++] = sect;
692 g_assert (num_sections < num);
693 if (strcmp (sect->name, ".text") == 0) {
694 sect->shidx = SECT_TEXT;
695 } else if (strcmp (sect->name, ".data") == 0) {
696 sect->shidx = SECT_DATA;
697 } else if (strcmp (sect->name, ".bss") == 0) {
698 sect->shidx = SECT_BSS;
701 maxs = MAX (maxs, sect->subsection);
703 for (i = 0; i < num_sections; i++) {
704 for (j = 1; j <= maxs; ++j) {
705 for (sect = acfg->sections; sect; sect = sect->next) {
706 if (sect->subsection == j && strcmp (out [i]->name, sect->name) == 0) {
707 append_subsection (acfg, sheaders, out [i], sect);
716 elf_hash (const unsigned char *name)
718 unsigned long h = 0, g;
720 h = (h << 4) + *name++;
721 if ((g = h & 0xf0000000))
728 #define NUM_BUCKETS 17
731 build_hash (MonoAotCompile *acfg, int num_sections, ElfStrTable *dynstr)
734 int num_symbols = 1 + num_sections + 3;
737 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
738 if (!symbol->is_global)
741 str_table_add (dynstr, symbol->name);
742 /*g_print ("adding sym: %s\n", symbol->name);*/
744 str_table_add (dynstr, "__bss_start");
745 str_table_add (dynstr, "_edata");
746 str_table_add (dynstr, "_end");
748 data = g_new0 (int, num_symbols + 2 + NUM_BUCKETS);
749 data [0] = NUM_BUCKETS;
750 data [1] = num_symbols;
756 get_label_addr (MonoAotCompile *acfg, const char *name)
763 lab = g_hash_table_lookup (acfg->labels, name);
764 section = lab->section;
765 offset = lab->offset;
766 if (section->parent) {
767 value = section->parent->file_offset + section->cur_offset + offset;
769 value = section->file_offset + offset;
775 collect_syms (MonoAotCompile *acfg, int *hash, ElfStrTable *strtab, struct ElfSectHeader *sheaders, int *num_syms)
786 symbols = g_new0 (ElfSymbol, hash [1]);
788 symbols = g_new0 (ElfSymbol, *num_syms + SECT_NUM + 10); /* FIXME */
790 /* the first symbol is undef, all zeroes */
794 for (j = 1; j < SECT_NUM; ++j) {
795 symbols [i].st_info = SYM_LOCAL | SYM_SECTION;
796 symbols [i].st_shndx = j;
797 symbols [i].st_value = sheaders [j].sh_addr;
801 for (section = acfg->sections; section; section = section->next) {
804 symbols [i].st_info = SYM_LOCAL | SYM_SECTION;
805 if (strcmp (section->name, ".text") == 0) {
806 symbols [i].st_shndx = SECT_TEXT;
807 section->shidx = SECT_TEXT;
808 section->file_offset = 4096;
809 symbols [i].st_value = section->file_offset;
810 } else if (strcmp (section->name, ".data") == 0) {
811 symbols [i].st_shndx = SECT_DATA;
812 section->shidx = SECT_DATA;
813 section->file_offset = 4096 + 28; /* FIXME */
814 symbols [i].st_value = section->file_offset;
815 } else if (strcmp (section->name, ".bss") == 0) {
816 symbols [i].st_shndx = SECT_BSS;
817 section->shidx = SECT_BSS;
818 section->file_offset = 4096 + 28 + 8; /* FIXME */
819 symbols [i].st_value = section->file_offset;
824 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
827 if (!symbol->is_global)
829 symbols [i].st_info = (symbol->is_function? SYM_FUNC : SYM_OBJECT) | SYM_GLOBAL;
830 symbols [i].st_name = str_table_add (strtab, symbol->name);
831 /*g_print ("sym name %s tabled to %d\n", symbol->name, symbols [i].st_name);*/
832 section = symbol->section;
833 symbols [i].st_shndx = section->parent? section->parent->shidx: section->shidx;
834 lab = g_hash_table_lookup (acfg->labels, symbol->name);
835 offset = lab->offset;
836 if (section->parent) {
837 symbols [i].st_value = section->parent->file_offset + section->cur_offset + offset;
839 symbols [i].st_value = section->file_offset + offset;
843 /* add special symbols */
844 symbols [i].st_name = str_table_add (strtab, "__bss_start");
845 symbols [i].st_shndx = 0xfff1;
846 symbols [i].st_info = SYM_GLOBAL;
848 symbols [i].st_name = str_table_add (strtab, "_edata");
849 symbols [i].st_shndx = 0xfff1;
850 symbols [i].st_info = SYM_GLOBAL;
852 symbols [i].st_name = str_table_add (strtab, "_end");
853 symbols [i].st_shndx = 0xfff1;
854 symbols [i].st_info = SYM_GLOBAL;
860 /* add to hash table */
863 chain = hash + 2 + hash [0];
864 for (i = 0; i < hash [1]; ++i) {
866 /*g_print ("checking %d '%s' (sym %d)\n", symbols [i].st_name, strtab->data->str + symbols [i].st_name, i);*/
867 if (!symbols [i].st_name)
869 hashc = elf_hash ((guint8*)strtab->data->str + symbols [i].st_name);
870 slot = hashc % hash [0];
871 /*g_print ("hashing '%s' at slot %d (sym %d)\n", strtab->data->str + symbols [i].st_name, slot, i);*/
873 chain [i] = bucket [slot];
884 reloc_symbols (MonoAotCompile *acfg, ElfSymbol *symbols, struct ElfSectHeader *sheaders, ElfStrTable *strtab, gboolean dynamic)
892 for (section = acfg->sections; section; section = section->next) {
895 symbols [i].st_value = sheaders [section->shidx].sh_addr;
899 for (i = 1; i < SECT_NUM; ++i) {
900 symbols [i].st_value = sheaders [i].sh_addr;
903 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
906 if (dynamic && !symbol->is_global)
908 section = symbol->section;
909 lab = g_hash_table_lookup (acfg->labels, symbol->name);
910 offset = lab->offset;
911 if (section->parent) {
912 symbols [i].st_value = sheaders [section->parent->shidx].sh_addr + section->cur_offset + offset;
914 symbols [i].st_value = sheaders [section->shidx].sh_addr + offset;
919 symbols [i].st_value = sheaders [SECT_BSS].sh_addr;
922 symbols [i].st_value = sheaders [SECT_DATA].sh_addr + sheaders [SECT_DATA].sh_size;
925 symbols [i].st_value = sheaders [SECT_BSS].sh_addr + sheaders [SECT_BSS].sh_size;
930 resolve_relocations (MonoAotCompile *acfg)
934 gsize end_val, start_val;
939 rr = g_new0 (ElfReloc, acfg->num_relocs);
942 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
943 end_val = get_label_addr (acfg, reloc->val1);
945 start_val = get_label_addr (acfg, reloc->val2);
946 } else if (reloc->val2_section) {
947 start_val = reloc->val2_offset;
948 if (reloc->val2_section->parent)
949 start_val += reloc->val2_section->parent->file_offset + reloc->val2_section->cur_offset;
951 start_val += reloc->val2_section->file_offset;
955 end_val = end_val - start_val + reloc->offset;
956 if (reloc->section->parent) {
957 data = reloc->section->parent->data;
958 data += reloc->section->cur_offset;
959 data += reloc->section_offset;
960 vaddr = reloc->section->parent->file_offset;
961 vaddr += reloc->section->cur_offset;
962 vaddr += reloc->section_offset;
964 data = reloc->section->data;
965 data += reloc->section_offset;
966 vaddr = reloc->section->file_offset;
967 vaddr += reloc->section_offset;
969 /* FIXME: little endian */
971 data [1] = end_val >> 8;
972 data [2] = end_val >> 16;
973 data [3] = end_val >> 24;
974 if (start_val == 0) {
976 rr [i].value = 8; /* FIXME: 386_RELATIVE */
978 g_assert (i <= acfg->num_relocs);
985 emit_writeout (MonoAotCompile *acfg)
987 char *outfile_name, *tmp_outfile_name;
989 struct ElfHeader header;
990 struct ElfProgHeader progh [3];
991 struct ElfSectHeader secth [SECT_NUM];
993 ElfStrTable str_table = {NULL, NULL};
994 ElfStrTable sh_str_table = {NULL, NULL};
995 ElfStrTable dyn_str_table = {NULL, NULL};
996 BinSection* sections [6];
997 BinSection *text_section = NULL, *data_section = NULL, *bss_section = NULL;
1000 ElfDynamic dynamic [14];
1002 int i, num_sections, file_offset, virt_offset, size, num_symtab;
1005 if (acfg->aot_opts.outfile)
1006 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1008 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1010 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1012 unlink (tmp_outfile_name);
1013 file = fopen (tmp_outfile_name, "w");
1016 /* Section headers */
1017 memset (§h, 0, sizeof (secth));
1018 memset (&dynamic, 0, sizeof (dynamic));
1019 memset (&header, 0, sizeof (header));
1021 for (i = 1; i < SECT_NUM; ++i) {
1022 secth [i].sh_name = str_table_add (&sh_str_table, section_names [i]);
1023 secth [i].sh_type = section_type [i];
1024 secth [i].sh_link = section_link [i];
1025 secth [i].sh_addralign = section_align [i];
1026 secth [i].sh_flags = section_flags [i];
1027 secth [i].sh_entsize = section_esize [i];
1029 secth [SECT_DYNSYM].sh_info = 4;
1030 secth [SECT_SYMTAB].sh_info = 20;
1032 num_sections = collect_sections (acfg, secth, sections, 6);
1033 hash = build_hash (acfg, num_sections, &dyn_str_table);
1034 num_symtab = hash [1]; /* FIXME */
1035 g_print ("num_sections: %d\n", num_sections);
1036 g_print ("dynsym: %d, dynstr size: %d\n", hash [1], dyn_str_table.data->len);
1037 for (i = 0; i < num_sections; ++i) {
1038 g_print ("section %s, size: %d, %x\n", sections [i]->name, sections [i]->cur_offset, sections [i]->cur_offset);
1041 /* at this point we know where in the file the first segment sections go */
1042 dynsym = collect_syms (acfg, hash, &dyn_str_table, NULL, NULL);
1043 num_local_syms = hash [1];
1044 symtab = collect_syms (acfg, NULL, &str_table, secth, &num_local_syms);
1046 for (i = 0; i < num_sections; ++i) {
1047 if (sections [i]->shidx == SECT_TEXT) {
1048 text_section = sections [i];
1049 } else if (sections [i]->shidx == SECT_DATA) {
1050 data_section = sections [i];
1051 } else if (sections [i]->shidx == SECT_BSS) {
1052 bss_section = sections [i];
1056 file_offset = virt_offset = sizeof (header) + sizeof (progh);
1057 secth [SECT_HASH].sh_addr = secth [SECT_HASH].sh_offset = file_offset;
1058 size = sizeof (int) * (2 + hash [0] + hash [1]);
1059 virt_offset = (file_offset += size);
1060 secth [SECT_HASH].sh_size = size;
1061 secth [SECT_DYNSYM].sh_addr = secth [SECT_DYNSYM].sh_offset = file_offset;
1062 size = sizeof (ElfSymbol) * hash [1];
1063 virt_offset = (file_offset += size);
1064 secth [SECT_DYNSYM].sh_size = size;
1065 secth [SECT_DYNSTR].sh_addr = secth [SECT_DYNSTR].sh_offset = file_offset;
1066 size = dyn_str_table.data->len;
1067 virt_offset = (file_offset += size);
1068 secth [SECT_DYNSTR].sh_size = size;
1070 file_offset &= ~(4-1);
1071 secth [SECT_REL_DYN].sh_addr = secth [SECT_REL_DYN].sh_offset = file_offset;
1072 size = sizeof (ElfReloc) * acfg->num_relocs;
1073 secth [SECT_REL_DYN].sh_size = size;
1074 virt_offset = (file_offset += size);
1075 secth [SECT_REL_DYN].sh_size = size;
1076 file_offset += 4096-1;
1077 file_offset &= ~(4096-1);
1078 virt_offset = file_offset;
1079 secth [SECT_TEXT].sh_addr = secth [SECT_TEXT].sh_offset = file_offset;
1080 size = text_section->cur_offset;
1081 secth [SECT_TEXT].sh_size = size;
1082 file_offset += size;
1084 file_offset &= ~(4-1);
1085 virt_offset = file_offset;
1086 /* .dynamic, .got.plt, .data, .bss here */
1087 secth [SECT_DYNAMIC].sh_addr = virt_offset;
1088 secth [SECT_DYNAMIC].sh_offset = file_offset;
1089 size = sizeof (dynamic);
1090 secth [SECT_DYNAMIC].sh_size = size;
1093 file_offset += size;
1094 virt_offset += size;
1095 secth [SECT_GOT_PLT].sh_addr = virt_offset;
1096 secth [SECT_GOT_PLT].sh_offset = file_offset;
1098 secth [SECT_GOT_PLT].sh_size = size;
1101 file_offset += size;
1102 virt_offset += size;
1103 secth [SECT_DATA].sh_addr = virt_offset;
1104 secth [SECT_DATA].sh_offset = file_offset;
1105 size = data_section->cur_offset;
1106 secth [SECT_DATA].sh_size = size;
1109 file_offset += size;
1110 virt_offset += size;
1111 secth [SECT_BSS].sh_addr = virt_offset;
1112 secth [SECT_BSS].sh_offset = file_offset;
1113 size = bss_section->cur_offset;
1114 secth [SECT_BSS].sh_size = size;
1116 /* virtual doesn't matter anymore */
1117 secth [SECT_SHSTRTAB].sh_offset = file_offset;
1118 size = sh_str_table.data->len;
1119 secth [SECT_SHSTRTAB].sh_size = size;
1122 file_offset += size;
1123 secth [SECT_SYMTAB].sh_offset = file_offset;
1124 size = sizeof (ElfSymbol) * num_local_syms;
1125 secth [SECT_SYMTAB].sh_size = size;
1126 file_offset += size;
1127 secth [SECT_STRTAB].sh_offset = file_offset;
1128 size = str_table.data->len;
1129 secth [SECT_STRTAB].sh_size = size;
1130 file_offset += size;
1132 file_offset &= ~(4-1);
1134 text_section->file_offset = secth [SECT_TEXT].sh_offset;
1135 data_section->file_offset = secth [SECT_DATA].sh_offset;
1136 bss_section->file_offset = secth [SECT_BSS].sh_offset;
1138 header.e_ident [0] = 0x7f; header.e_ident [1] = 'E';
1139 header.e_ident [2] = 'L'; header.e_ident [3] = 'F';
1140 header.e_ident [4] = SIZEOF_VOID_P == 4? 1: 2;
1141 header.e_ident [5] = 1; /* FIXME: little endian, bigendian is 2 */
1142 header.e_ident [6] = 1; /* version */
1143 header.e_ident [7] = 0; /* FIXME: */
1144 header.e_ident [8] = 0; /* FIXME: */
1145 for (i = 9; i < 16; ++i)
1146 header.e_ident [i] = 0;
1148 header.e_type = 3; /* shared library */
1149 header.e_machine = 3; /* FIXME: 386 */
1150 header.e_version = 1; /* FIXME: */
1152 header.e_phoff = sizeof (header);
1153 header.e_ehsize = sizeof (header);
1154 header.e_phentsize = sizeof (struct ElfProgHeader);
1156 header.e_entry = secth [SECT_TEXT].sh_addr;
1157 header.e_shstrndx = 10;
1158 header.e_shentsize = sizeof (struct ElfSectHeader);
1159 header.e_shnum = SECT_NUM;
1160 header.e_shoff = file_offset;
1164 dynamic [i].d_tag = DYN_HASH;
1165 dynamic [i].d_val = secth [SECT_HASH].sh_offset;
1167 dynamic [i].d_tag = DYN_STRTAB;
1168 dynamic [i].d_val = secth [SECT_DYNSTR].sh_offset;
1170 dynamic [i].d_tag = DYN_SYMTAB;
1171 dynamic [i].d_val = secth [SECT_DYNSYM].sh_offset;
1173 dynamic [i].d_tag = DYN_STRSZ;
1174 dynamic [i].d_val = dyn_str_table.data->len;
1176 dynamic [i].d_tag = DYN_SYMENT;
1177 dynamic [i].d_val = sizeof (ElfSymbol);
1179 dynamic [i].d_tag = DYN_REL;
1180 dynamic [i].d_val = secth [SECT_REL_DYN].sh_offset;
1182 dynamic [i].d_tag = DYN_RELSZ;
1183 dynamic [i].d_val = secth [SECT_REL_DYN].sh_size;
1185 dynamic [i].d_tag = DYN_RELENT;
1186 dynamic [i].d_val = sizeof (ElfReloc);
1188 dynamic [i].d_tag = DYN_RELCOUNT;
1189 dynamic [i].d_val = acfg->num_relocs;
1192 /* Program header */
1193 memset (&progh, 0, sizeof (progh));
1194 progh [0].p_type = 1; /* LOAD */
1195 progh [0].p_filesz = progh [0].p_memsz = secth [SECT_DYNAMIC].sh_offset;
1196 progh [0].p_align = 4096;
1197 progh [0].p_flags = 5;
1199 progh [1].p_type = 1;
1200 progh [1].p_offset = secth [SECT_DYNAMIC].sh_offset;
1201 progh [1].p_vaddr = progh [1].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1202 progh [1].p_filesz = secth [SECT_BSS].sh_offset - secth [SECT_DYNAMIC].sh_offset;
1203 progh [1].p_memsz = secth [SECT_BSS].sh_addr + secth [SECT_BSS].sh_size - secth [SECT_DYNAMIC].sh_addr;
1204 progh [1].p_align = 4096;
1205 progh [1].p_flags = 6;
1207 progh [2].p_type = 2; /* DYNAMIC */
1208 progh [2].p_offset = secth [SECT_DYNAMIC].sh_offset;
1209 progh [2].p_vaddr = progh [2].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1210 progh [2].p_filesz = progh [2].p_memsz = secth [SECT_DYNAMIC].sh_size;
1211 progh [2].p_align = 4;
1212 progh [2].p_flags = 6;
1214 reloc_symbols (acfg, dynsym, secth, &dyn_str_table, TRUE);
1215 reloc_symbols (acfg, symtab, secth, &str_table, FALSE);
1216 relocs = resolve_relocations (acfg);
1218 fwrite (&header, sizeof (header), 1, file);
1219 fwrite (&progh, sizeof (progh), 1, file);
1220 fwrite (hash, sizeof (int) * (hash [0] + hash [1] + 2), 1, file);
1221 fwrite (dynsym, sizeof (ElfSymbol) * hash [1], 1, file);
1222 fwrite (dyn_str_table.data->str, dyn_str_table.data->len, 1, file);
1224 fseek (file, secth [SECT_REL_DYN].sh_offset, SEEK_SET);
1225 fwrite (relocs, sizeof (ElfReloc), acfg->num_relocs, file);
1227 fseek (file, secth [SECT_TEXT].sh_offset, SEEK_SET);
1228 /* write .text, .data, .bss sections */
1229 fwrite (text_section->data, text_section->cur_offset, 1, file);
1232 fwrite (dynamic, sizeof (dynamic), 1, file);
1234 size = secth [SECT_DYNAMIC].sh_addr;
1235 fwrite (&size, sizeof (size), 1, file);
1236 fseek (file, secth [SECT_DATA].sh_offset, SEEK_SET);
1237 fwrite (data_section->data, data_section->cur_offset, 1, file);
1239 fseek (file, secth [SECT_SHSTRTAB].sh_offset, SEEK_SET);
1240 fwrite (sh_str_table.data->str, sh_str_table.data->len, 1, file);
1241 fseek (file, secth [SECT_SYMTAB].sh_offset, SEEK_SET);
1242 fwrite (symtab, sizeof (ElfSymbol) * num_local_syms, 1, file);
1243 fseek (file, secth [SECT_STRTAB].sh_offset, SEEK_SET);
1244 fwrite (str_table.data->str, str_table.data->len, 1, file);
1245 /*g_print ("file_offset %d vs %d\n", file_offset, ftell (file));*/
1246 /*g_assert (file_offset >= ftell (file));*/
1247 fseek (file, file_offset, SEEK_SET);
1248 fwrite (§h, sizeof (secth), 1, file);
1250 rename (tmp_outfile_name, outfile_name);
1252 g_free (tmp_outfile_name);
1253 g_free (outfile_name);
1258 #endif /* USE_ELF_WRITER */
1263 emit_start (MonoAotCompile *acfg)
1265 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
1266 acfg->fp = fdopen (i, "w+");
1267 g_assert (acfg->fp);
1271 emit_unset_mode (MonoAotCompile *acfg)
1273 if (acfg->mode == EMIT_NONE)
1275 fprintf (acfg->fp, "\n");
1276 acfg->mode = EMIT_NONE;
1280 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
1282 emit_unset_mode (acfg);
1283 #if defined(PLATFORM_WIN32)
1284 fprintf (acfg->fp, ".section %s\n", section_name);
1285 #elif defined(sparc) || defined(__arm__)
1286 /* For solaris as, GNU as should accept the same */
1287 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1288 #elif defined(__ppc__) && defined(__MACH__)
1289 /* This needs to be made more precise on mach. */
1290 fprintf (acfg->fp, "%s\n", subsection_index == 0 ? ".text" : ".data");
1292 fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1297 emit_symbol_type (MonoAotCompile *acfg, const char *name, gboolean func)
1306 emit_unset_mode (acfg);
1307 #if defined(sparc) || defined(__arm__)
1308 fprintf (acfg->fp, "\t.type %s,#%s\n", name, stype);
1309 #elif defined(PLATFORM_WIN32)
1311 #elif !(defined(__ppc__) && defined(__MACH__))
1312 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1313 #elif defined(__x86_64__) || defined(__i386__)
1314 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1319 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
1321 emit_unset_mode (acfg);
1322 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1323 // mach-o always uses a '_' prefix.
1324 fprintf (acfg->fp, "\t.globl _%s\n", name);
1326 fprintf (acfg->fp, "\t.globl %s\n", name);
1329 emit_symbol_type (acfg, name, func);
1333 emit_label (MonoAotCompile *acfg, const char *name)
1335 emit_unset_mode (acfg);
1336 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1337 // mach-o always uses a '_' prefix.
1338 fprintf (acfg->fp, "_%s:\n", name);
1340 fprintf (acfg->fp, "%s:\n", name);
1343 #if defined(PLATFORM_WIN32)
1344 /* Emit a normal label too */
1345 fprintf (acfg->fp, "%s:\n", name);
1350 emit_string (MonoAotCompile *acfg, const char *value)
1352 emit_unset_mode (acfg);
1353 fprintf (acfg->fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
1357 emit_line (MonoAotCompile *acfg)
1359 emit_unset_mode (acfg);
1360 fprintf (acfg->fp, "\n");
1364 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
1366 emit_unset_mode (acfg);
1367 emit_section_change (acfg, ".text", 1);
1368 emit_global (acfg, name, FALSE);
1369 emit_label (acfg, name);
1370 emit_string (acfg, value);
1374 emit_alignment (MonoAotCompile *acfg, int size)
1376 emit_unset_mode (acfg);
1377 #if defined(__arm__)
1378 fprintf (acfg->fp, "\t.align %d\n", ilog2 (size));
1379 #elif defined(__ppc__) && defined(__MACH__)
1380 // the mach-o assembler specifies alignments as powers of 2.
1381 fprintf (acfg->fp, "\t.align %d\t; ilog2\n", ilog2(size));
1382 #elif defined(__powerpc__)
1383 /* ignore on linux/ppc */
1385 fprintf (acfg->fp, "\t.align %d\n", size);
1390 emit_pointer (MonoAotCompile *acfg, const char *target)
1392 emit_unset_mode (acfg);
1393 emit_alignment (acfg, sizeof (gpointer));
1394 #if defined(__x86_64__)
1395 fprintf (acfg->fp, "\t.quad %s\n", target ? target : "0");
1396 #elif defined(sparc) && SIZEOF_VOID_P == 8
1397 fprintf (acfg->fp, "\t.xword %s\n", target ? target : "0");
1399 fprintf (acfg->fp, "\t.long %s\n", target ? target : "0");
1404 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
1407 if (acfg->mode != EMIT_BYTE) {
1408 acfg->mode = EMIT_BYTE;
1409 acfg->col_count = 0;
1411 for (i = 0; i < size; ++i, ++acfg->col_count) {
1412 if ((acfg->col_count % 32) == 0)
1413 fprintf (acfg->fp, "\n\t.byte ");
1415 fprintf (acfg->fp, ",");
1416 fprintf (acfg->fp, "0x%x", buf [i]);
1421 emit_int16 (MonoAotCompile *acfg, int value)
1423 if (acfg->mode != EMIT_WORD) {
1424 acfg->mode = EMIT_WORD;
1425 acfg->col_count = 0;
1427 if ((acfg->col_count++ % 8) == 0)
1428 #if defined(__arm__)
1429 /* FIXME: Use .hword on other archs as well */
1430 fprintf (acfg->fp, "\n\t.hword ");
1432 fprintf (acfg->fp, "\n\t.word ");
1435 fprintf (acfg->fp, ", ");
1436 fprintf (acfg->fp, "%d", value);
1440 emit_int32 (MonoAotCompile *acfg, int value)
1442 if (acfg->mode != EMIT_LONG) {
1443 acfg->mode = EMIT_LONG;
1444 acfg->col_count = 0;
1446 if ((acfg->col_count++ % 8) == 0)
1447 fprintf (acfg->fp, "\n\t.long ");
1449 fprintf (acfg->fp, ",");
1450 fprintf (acfg->fp, "%d", value);
1454 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
1456 if (acfg->mode != EMIT_LONG) {
1457 acfg->mode = EMIT_LONG;
1458 acfg->col_count = 0;
1460 if ((acfg->col_count++ % 8) == 0)
1461 fprintf (acfg->fp, "\n\t.long ");
1463 fprintf (acfg->fp, ",");
1465 fprintf (acfg->fp, "%s - %s + %d", end, start, offset);
1466 else if (offset < 0)
1467 fprintf (acfg->fp, "%s - %s %d", end, start, offset);
1469 fprintf (acfg->fp, "%s - %s", end, start);
1473 emit_zero_bytes (MonoAotCompile *acfg, int num)
1475 emit_unset_mode (acfg);
1476 fprintf (acfg->fp, "\t.skip %d\n", num);
1480 emit_writeout (MonoAotCompile *acfg)
1482 char *command, *objfile;
1483 char *outfile_name, *tmp_outfile_name;
1487 #if defined(__x86_64__)
1488 #define AS_OPTIONS "--64"
1489 #elif defined(sparc) && SIZEOF_VOID_P == 8
1490 #define AS_OPTIONS "-xarch=v9"
1492 #define AS_OPTIONS ""
1494 command = g_strdup_printf ("as %s %s -o %s.o", AS_OPTIONS, acfg->tmpfname, acfg->tmpfname);
1495 printf ("Executing the native assembler: %s\n", command);
1496 if (system (command) != 0) {
1503 if (acfg->aot_opts.outfile)
1504 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1506 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1508 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1511 command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
1512 #elif defined(__ppc__) && defined(__MACH__)
1513 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
1514 #elif defined(PLATFORM_WIN32)
1515 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
1517 if (acfg->aot_opts.no_dlsym) {
1519 * Need to link using gcc so our ctor function gets called.
1521 command = g_strdup_printf ("gcc -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1523 command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1526 printf ("Executing the native linker: %s\n", command);
1527 if (system (command) != 0) {
1528 g_free (tmp_outfile_name);
1529 g_free (outfile_name);
1535 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
1538 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
1539 printf ("Stripping the binary: %s\n", com);
1543 rename (tmp_outfile_name, outfile_name);
1545 g_free (tmp_outfile_name);
1546 g_free (outfile_name);
1548 if (acfg->aot_opts.save_temps)
1549 printf ("Retained input file.\n");
1551 unlink (acfg->tmpfname);
1556 #endif /* ASM_WRITER */
1559 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
1561 if (acfg->aot_opts.no_dlsym) {
1562 g_ptr_array_add (acfg->globals, g_strdup (name));
1564 emit_global_inner (acfg, name, func);
1569 emit_byte (MonoAotCompile *acfg, guint8 val)
1571 emit_bytes (acfg, &val, 1);
1575 mono_get_field_token (MonoClassField *field)
1577 MonoClass *klass = field->parent;
1580 for (i = 0; i < klass->field.count; ++i) {
1581 if (field == &klass->fields [i])
1582 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1585 g_assert_not_reached ();
1590 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1594 //printf ("ENCODE: %d 0x%x.\n", value, value);
1597 * Same encoding as the one used in the metadata, extended to handle values
1598 * greater than 0x1fffffff.
1600 if ((value >= 0) && (value <= 127))
1602 else if ((value >= 0) && (value <= 16383)) {
1603 p [0] = 0x80 | (value >> 8);
1604 p [1] = value & 0xff;
1606 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1607 p [0] = (value >> 24) | 0xc0;
1608 p [1] = (value >> 16) & 0xff;
1609 p [2] = (value >> 8) & 0xff;
1610 p [3] = value & 0xff;
1615 p [1] = (value >> 24) & 0xff;
1616 p [2] = (value >> 16) & 0xff;
1617 p [3] = (value >> 8) & 0xff;
1618 p [4] = value & 0xff;
1626 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1630 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1634 index = g_hash_table_size (cfg->image_hash);
1635 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1636 g_ptr_array_add (cfg->image_table, image);
1642 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1645 MonoClass *k = NULL;
1647 /* FIXME: Search referenced images as well */
1648 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1649 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1654 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1655 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1661 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1663 if (klass->generic_class) {
1665 g_assert (klass->type_token);
1667 /* Find a typespec for a class if possible */
1668 token = find_typespec_for_class (acfg, klass);
1670 encode_value (token, buf, &buf);
1671 encode_value (get_image_index (acfg, acfg->image), buf, &buf);
1673 MonoClass *gclass = klass->generic_class->container_class;
1674 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1677 /* Encode it ourselves */
1679 encode_value (MONO_TOKEN_TYPE_SPEC, buf, &buf);
1680 encode_klass_ref (acfg, gclass, buf, &buf);
1681 encode_value (inst->type_argc, buf, &buf);
1682 for (i = 0; i < inst->type_argc; ++i)
1683 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), buf, &buf);
1685 } else if (klass->type_token) {
1686 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1687 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, buf, &buf);
1688 encode_value (get_image_index (acfg, klass->image), buf, &buf);
1691 g_assert (klass->rank > 0);
1692 encode_value (MONO_TOKEN_TYPE_DEF, buf, &buf);
1693 encode_value (get_image_index (acfg, klass->image), buf, &buf);
1694 encode_value (klass->rank, buf, &buf);
1695 encode_klass_ref (acfg, klass->element_class, buf, &buf);
1701 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1703 guint32 token = mono_get_field_token (field);
1705 encode_klass_ref (cfg, field->parent, buf, &buf);
1706 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1707 encode_value (token - MONO_TOKEN_FIELD_DEF, buf, &buf);
1713 find_methodspec_for_method (MonoAotCompile *acfg, MonoMethod *method)
1716 MonoMethod *m = NULL;
1718 /* FIXME: Search referenced images as well */
1719 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
1720 /* Since we don't compile generic methods, the context is empty */
1721 m = mono_get_method_full (acfg->image, MONO_TOKEN_METHOD_SPEC | (i + 1), NULL, NULL);
1726 g_assert (i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows);
1728 return MONO_TOKEN_METHOD_SPEC | (i + 1);
1733 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1735 guint32 image_index = get_image_index (acfg, method->klass->image);
1736 guint32 token = method->token;
1737 MonoJumpInfoToken *ji;
1739 g_assert (image_index < 255);
1741 if (mono_method_signature (method)->is_inflated) {
1743 * This is a generic method, find the original token which referenced it and
1746 /* This doesn't work for some reason */
1748 image_index = get_image_index (acfg, acfg->image);
1749 g_assert (image_index < 255);
1750 token = find_methodspec_for_method (acfg, method);
1752 /* Obtain the token from information recorded by the JIT */
1753 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1755 image_index = get_image_index (acfg, ji->image);
1756 g_assert (image_index < 255);
1760 encode_value ((255 << 24), buf, &buf);
1761 encode_value (image_index, buf, &buf);
1762 encode_value (token, buf, &buf);
1763 } else if (token == 0) {
1764 /* This might be a method of a constructed type like int[,].Set */
1765 /* Obtain the token from information recorded by the JIT */
1766 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1768 image_index = get_image_index (acfg, ji->image);
1769 g_assert (image_index < 255);
1773 encode_value ((255 << 24), buf, &buf);
1774 encode_value (image_index, buf, &buf);
1775 encode_value (token, buf, &buf);
1777 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1778 encode_value ((image_index << 24) | mono_metadata_token_index (token), buf, &buf);
1784 compare_patches (gconstpointer a, gconstpointer b)
1788 i = (*(MonoJumpInfo**)a)->ip.i;
1789 j = (*(MonoJumpInfo**)b)->ip.i;
1801 get_plt_index (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1805 GHashTable *hash = acfg->patch_to_plt_offset;
1807 switch (patch_info->type) {
1808 case MONO_PATCH_INFO_METHOD:
1809 case MONO_PATCH_INFO_WRAPPER:
1810 case MONO_PATCH_INFO_INTERNAL_METHOD:
1811 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1812 case MONO_PATCH_INFO_CLASS_INIT: {
1813 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1814 gpointer patch_id = NULL;
1816 /* First check for an existing patch */
1817 switch (patch_info->type) {
1818 case MONO_PATCH_INFO_METHOD:
1819 patch_id = patch_info->data.method;
1821 case MONO_PATCH_INFO_INTERNAL_METHOD:
1822 patch_id = (gpointer)patch_info->data.name;
1824 case MONO_PATCH_INFO_CLASS_INIT:
1825 patch_id = patch_info->data.klass;
1827 case MONO_PATCH_INFO_WRAPPER:
1828 hash = acfg->patch_to_plt_offset_wrapper [patch_info->data.method->wrapper_type];
1830 acfg->patch_to_plt_offset_wrapper [patch_info->data.method->wrapper_type] = g_hash_table_new (NULL, NULL);
1831 hash = acfg->patch_to_plt_offset_wrapper [patch_info->data.method->wrapper_type];
1833 patch_id = patch_info->data.method;
1835 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1836 /* Each addr should only occur once */
1839 g_assert_not_reached ();
1843 idx = GPOINTER_TO_UINT (g_hash_table_lookup (hash, patch_id));
1847 g_hash_table_insert (hash, patch_id, GUINT_TO_POINTER (acfg->plt_offset));
1851 res = acfg->plt_offset;
1852 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (acfg->plt_offset), new_ji);
1853 acfg->plt_offset ++;
1856 /* Nullify the patch */
1857 patch_info->type = MONO_PATCH_INFO_NONE;
1869 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1870 * JI could be found if it exists, otherwise allocates a new one.
1873 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1877 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
1879 return got_offset - 1;
1881 got_offset = acfg->got_offset;
1882 acfg->got_offset ++;
1884 acfg->stats.got_slots ++;
1885 acfg->stats.got_slot_types [ji->type] ++;
1891 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1896 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
1897 got_offset = get_got_offset (acfg, ji);
1898 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
1899 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
1900 g_ptr_array_add (acfg->shared_patches, copy);
1903 return get_got_offset (acfg, ji);
1906 /* Add a method to the list of methods which need to be emitted */
1908 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
1910 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1911 g_ptr_array_add (acfg->methods, method);
1912 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1917 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1919 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1927 add_method (MonoAotCompile *acfg, MonoMethod *method)
1929 int index = acfg->method_index;
1931 add_method_with_index (acfg, method, index);
1933 /* FIXME: Fix quadratic behavior */
1934 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1936 acfg->method_index ++;
1942 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1944 MonoAotCompile *acfg = user_data;
1945 MonoJitICallInfo *callinfo = value;
1946 MonoMethod *wrapper;
1952 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1953 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1956 add_method (acfg, wrapper);
1960 get_runtime_invoke_sig (MonoMethodSignature *sig)
1962 MonoMethodBuilder *mb;
1965 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1966 m = mono_mb_create_method (mb, sig, 16);
1967 return mono_marshal_get_runtime_invoke (m);
1971 add_wrappers (MonoAotCompile *acfg)
1975 MonoMethodSignature *csig;
1978 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1979 * so there is only one wrapper of a given type, or inlining their contents into their
1984 * FIXME: This depends on the fact that different wrappers have different
1988 /* FIXME: Collect these automatically */
1990 /* Runtime invoke wrappers */
1992 /* void runtime-invoke () [.cctor] */
1993 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1994 csig->ret = &mono_defaults.void_class->byval_arg;
1995 add_method (acfg, get_runtime_invoke_sig (csig));
1997 /* void runtime-invoke () [Finalize] */
1998 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2000 csig->ret = &mono_defaults.void_class->byval_arg;
2001 add_method (acfg, get_runtime_invoke_sig (csig));
2003 /* void runtime-invoke (string) [exception ctor] */
2004 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2006 csig->ret = &mono_defaults.void_class->byval_arg;
2007 csig->params [0] = &mono_defaults.string_class->byval_arg;
2008 add_method (acfg, get_runtime_invoke_sig (csig));
2010 /* void runtime-invoke (string, string) [exception ctor] */
2011 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2013 csig->ret = &mono_defaults.void_class->byval_arg;
2014 csig->params [0] = &mono_defaults.string_class->byval_arg;
2015 csig->params [1] = &mono_defaults.string_class->byval_arg;
2016 add_method (acfg, get_runtime_invoke_sig (csig));
2018 /* string runtime-invoke () [Exception.ToString ()] */
2019 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2021 csig->ret = &mono_defaults.string_class->byval_arg;
2022 add_method (acfg, get_runtime_invoke_sig (csig));
2024 /* void runtime-invoke (string, Exception) [exception ctor] */
2025 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2027 csig->ret = &mono_defaults.void_class->byval_arg;
2028 csig->params [0] = &mono_defaults.string_class->byval_arg;
2029 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2030 add_method (acfg, get_runtime_invoke_sig (csig));
2032 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2033 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2035 csig->ret = &(mono_class_from_name (
2036 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2037 csig->params [0] = &mono_defaults.string_class->byval_arg;
2038 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2039 add_method (acfg, get_runtime_invoke_sig (csig));
2041 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2043 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2045 method = mono_get_method (acfg->image, token, NULL);
2047 if (!strcmp (method->name, "Main"))
2048 add_method (acfg, mono_marshal_get_runtime_invoke (method));
2051 /* JIT icall wrappers */
2052 /* FIXME: locking */
2053 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2055 /* Managed Allocators */
2056 nallocators = mono_gc_get_managed_allocator_types ();
2057 for (i = 0; i < nallocators; ++i) {
2058 m = mono_gc_get_managed_allocator_by_type (i);
2060 add_method (acfg, m);
2064 add_method (acfg, mono_marshal_get_stelemref ());
2066 /* remoting-invoke wrappers */
2067 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2069 MonoMethodSignature *sig;
2070 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2072 method = mono_get_method (acfg->image, token, NULL);
2074 sig = mono_method_signature (method);
2076 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
2077 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2078 m = mono_marshal_get_remoting_invoke_with_check (method);
2080 add_method (acfg, m);
2086 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2088 int i, pindex, start_index, method_index;
2090 MonoJumpInfo *patch_info;
2091 MonoMethodHeader *header;
2096 header = mono_method_get_header (method);
2098 method_index = get_method_index (acfg, method);
2101 /* Collect and sort relocations */
2102 patches = g_ptr_array_new ();
2103 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2104 g_ptr_array_add (patches, patch_info);
2105 g_ptr_array_sort (patches, compare_patches);
2108 for (i = 0; i < code_len; i++) {
2110 for (pindex = start_index; pindex < patches->len; ++pindex) {
2111 patch_info = g_ptr_array_index (patches, pindex);
2112 if (patch_info->ip.i >= i)
2116 #ifdef MONO_ARCH_AOT_SUPPORTED
2118 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2119 start_index = pindex;
2121 switch (patch_info->type) {
2122 case MONO_PATCH_INFO_NONE:
2124 case MONO_PATCH_INFO_GOT_OFFSET: {
2125 guint32 offset = mono_arch_get_patch_offset (code + i);
2126 emit_bytes (acfg, code + i, offset);
2127 emit_symbol_diff (acfg, "got", ".", offset);
2129 i += offset + 4 - 1;
2135 char *direct_call_target;
2137 if (!is_got_patch (patch_info->type))
2141 * If this patch is a call, try emitting a direct call instead of
2142 * through a PLT entry. This is possible if the called method is in
2143 * the same assembly and requires no initialization.
2145 direct_call_target = NULL;
2146 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
2147 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2149 if (!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)) {
2150 //printf ("DIRECT: %s %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (callee_cfg->method, TRUE));
2151 direct_call_target = g_strdup_printf (".Lm_%x", get_method_index (acfg, callee_cfg->method));
2152 patch_info->type = MONO_PATCH_INFO_NONE;
2153 acfg->stats.direct_calls ++;
2157 acfg->stats.all_calls ++;
2160 if (!got_only && !direct_call_target) {
2161 plt_index = get_plt_index (acfg, patch_info);
2162 if (plt_index != -1) {
2163 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2164 direct_call_target = g_strdup_printf (".Lp_%d", plt_index);
2168 if (direct_call_target) {
2169 #if defined(__i386__) || defined(__x86_64__)
2170 g_assert (code [i] == 0xe8);
2171 /* Need to make sure this is exactly 5 bytes long */
2172 emit_byte (acfg, '\xe8');
2173 emit_symbol_diff (acfg, direct_call_target, ".", -4);
2175 #elif defined(__arm__)
2176 #ifdef USE_BIN_WRITER
2177 /* FIXME: Can't encode this using the current symbol writer functions */
2178 g_assert_not_reached ();
2180 emit_unset_mode (acfg);
2181 fprintf (acfg->fp, "bl %s\n", direct_call_target);
2186 g_free (direct_call_target);
2188 got_slot = get_got_offset (acfg, patch_info);
2190 emit_bytes (acfg, code + i, mono_arch_get_patch_offset (code + i));
2192 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
2193 #elif defined(__i386__)
2194 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
2195 #elif defined(__arm__)
2196 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
2198 g_assert_not_reached ();
2201 i += mono_arch_get_patch_offset (code + i) + 4 - 1;
2207 #endif /* MONO_ARCH_AOT_SUPPORTED */
2210 emit_bytes (acfg, code + i, 1);
2215 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2221 int func_alignment = 16;
2222 MonoMethodHeader *header;
2224 method = cfg->method;
2225 code = cfg->native_code;
2226 header = mono_method_get_header (method);
2228 method_index = get_method_index (acfg, method);
2230 /* Make the labels local */
2231 symbol = g_strdup_printf (".Lm_%x", method_index);
2233 emit_alignment (acfg, func_alignment);
2234 emit_label (acfg, symbol);
2235 if (acfg->aot_opts.write_symbols)
2236 emit_global (acfg, symbol, TRUE);
2238 if (cfg->verbose_level > 0)
2239 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2242 acfg->stats.code_size += cfg->code_len;
2244 acfg->method_got_offsets [method_index] = acfg->got_offset;
2246 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2254 * Encode PATCH_INFO into its disk representation. If SHARED is true, encode some types
2255 * of patches by allocating a GOT entry for them, and encode the GOT offset instead.
2258 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf, gboolean shared)
2262 switch (patch_info->type) {
2263 case MONO_PATCH_INFO_NONE:
2265 case MONO_PATCH_INFO_IMAGE:
2266 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2268 case MONO_PATCH_INFO_METHOD_REL:
2269 encode_value ((gint)patch_info->data.offset, p, &p);
2271 case MONO_PATCH_INFO_SWITCH: {
2272 gpointer *table = (gpointer *)patch_info->data.table->table;
2275 encode_value (patch_info->data.table->table_size, p, &p);
2276 for (k = 0; k < patch_info->data.table->table_size; k++)
2277 encode_value ((int)(gssize)table [k], p, &p);
2280 case MONO_PATCH_INFO_METHODCONST:
2281 case MONO_PATCH_INFO_METHOD:
2282 case MONO_PATCH_INFO_METHOD_JUMP:
2283 case MONO_PATCH_INFO_ICALL_ADDR:
2284 encode_method_ref (acfg, patch_info->data.method, p, &p);
2286 case MONO_PATCH_INFO_INTERNAL_METHOD:
2287 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2288 guint32 len = strlen (patch_info->data.name);
2290 encode_value (len, p, &p);
2292 memcpy (p, patch_info->data.name, len);
2297 case MONO_PATCH_INFO_LDSTR: {
2298 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2299 guint32 token = patch_info->data.token->token;
2300 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2301 encode_value (image_index, p, &p);
2302 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2305 case MONO_PATCH_INFO_RVA:
2306 case MONO_PATCH_INFO_DECLSEC:
2307 case MONO_PATCH_INFO_LDTOKEN:
2308 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2310 guint32 offset = get_got_offset (acfg, patch_info);
2311 encode_value (offset, p, &p);
2313 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2314 encode_value (patch_info->data.token->token, p, &p);
2317 case MONO_PATCH_INFO_EXC_NAME: {
2318 MonoClass *ex_class;
2321 mono_class_from_name (mono_defaults.exception_class->image,
2322 "System", patch_info->data.target);
2323 g_assert (ex_class);
2324 encode_klass_ref (acfg, ex_class, p, &p);
2327 case MONO_PATCH_INFO_R4:
2328 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2330 case MONO_PATCH_INFO_R8:
2331 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2332 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2334 case MONO_PATCH_INFO_VTABLE:
2335 case MONO_PATCH_INFO_CLASS:
2336 case MONO_PATCH_INFO_IID:
2337 case MONO_PATCH_INFO_ADJUSTED_IID:
2339 guint32 offset = get_got_offset (acfg, patch_info);
2340 encode_value (offset, p, &p);
2342 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2345 case MONO_PATCH_INFO_CLASS_INIT:
2346 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2347 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2349 case MONO_PATCH_INFO_FIELD:
2350 case MONO_PATCH_INFO_SFLDA:
2352 guint32 offset = get_got_offset (acfg, patch_info);
2353 encode_value (offset, p, &p);
2355 encode_field_info (acfg, patch_info->data.field, p, &p);
2358 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2360 case MONO_PATCH_INFO_WRAPPER:
2361 encode_value (patch_info->data.method->wrapper_type, p, &p);
2363 switch (patch_info->data.method->wrapper_type) {
2364 case MONO_WRAPPER_REMOTING_INVOKE:
2365 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2366 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2368 guint32 image_index;
2371 m = mono_marshal_method_from_wrapper (patch_info->data.method);
2372 image_index = get_image_index (acfg, m->klass->image);
2374 g_assert (image_index < 256);
2375 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2377 encode_value ((image_index << 24) + (mono_metadata_token_index (token)), p, &p);
2380 case MONO_WRAPPER_PROXY_ISINST:
2381 case MONO_WRAPPER_LDFLD:
2382 case MONO_WRAPPER_LDFLDA:
2383 case MONO_WRAPPER_STFLD:
2384 case MONO_WRAPPER_ISINST: {
2385 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (patch_info->data.method);
2386 encode_klass_ref (acfg, proxy_class, p, &p);
2389 case MONO_WRAPPER_LDFLD_REMOTE:
2390 case MONO_WRAPPER_STFLD_REMOTE:
2392 case MONO_WRAPPER_ALLOC: {
2393 int alloc_type = mono_gc_get_managed_allocator_type (patch_info->data.method);
2394 g_assert (alloc_type != -1);
2395 encode_value (alloc_type, p, &p);
2398 case MONO_WRAPPER_STELEMREF:
2401 g_assert_not_reached ();
2405 g_warning ("unable to handle jump info %d", patch_info->type);
2406 g_assert_not_reached ();
2413 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2416 guint32 last_offset, j, pindex;
2417 MonoJumpInfo *patch_info;
2419 encode_value (n_patches, p, &p);
2422 encode_value (first_got_offset, p, &p);
2424 /* First encode the type+position table */
2427 for (pindex = 0; pindex < patches->len; ++pindex) {
2429 patch_info = g_ptr_array_index (patches, pindex);
2431 if (patch_info->type == MONO_PATCH_INFO_NONE)
2436 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
2437 offset = patch_info->ip.i - last_offset;
2438 last_offset = patch_info->ip.i;
2440 /* Only the type is needed */
2441 *p = patch_info->type;
2445 /* Then encode the other info */
2446 for (pindex = 0; pindex < patches->len; ++pindex) {
2447 patch_info = g_ptr_array_index (patches, pindex);
2449 encode_patch (acfg, patch_info, p, &p, TRUE);
2456 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2460 int pindex, buf_size, n_patches;
2464 MonoJumpInfo *patch_info;
2465 MonoMethodHeader *header;
2466 guint32 method_index;
2468 guint32 first_got_offset;
2470 method = cfg->method;
2471 code = cfg->native_code;
2472 header = mono_method_get_header (method);
2474 method_index = get_method_index (acfg, method);
2476 /* Make the labels local */
2477 symbol = g_strdup_printf (".Lm_%x_p", method_index);
2479 /* Sort relocations */
2480 patches = g_ptr_array_new ();
2481 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2482 g_ptr_array_add (patches, patch_info);
2483 g_ptr_array_sort (patches, compare_patches);
2485 first_got_offset = acfg->method_got_offsets [method_index];
2487 /**********************/
2488 /* Encode method info */
2489 /**********************/
2491 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2492 p = buf = g_malloc (buf_size);
2494 if (mono_class_get_cctor (method->klass))
2495 encode_klass_ref (acfg, method->klass, p, &p);
2497 /* Not needed when loading the method */
2498 encode_value (0, p, &p);
2501 if (cfg->opt & MONO_OPT_SHARED) {
2502 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2503 for (l = cfg->ldstr_list; l; l = l->next) {
2504 encode_value ((long)l->data, p, &p);
2508 /* Used only in shared mode */
2509 g_assert (!cfg->ldstr_list);
2512 for (pindex = 0; pindex < patches->len; ++pindex) {
2513 patch_info = g_ptr_array_index (patches, pindex);
2515 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2516 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2517 patch_info->type = MONO_PATCH_INFO_NONE;
2522 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2523 /* Stored in a GOT slot initialized at module load time */
2524 patch_info->type = MONO_PATCH_INFO_NONE;
2528 if ((patch_info->type == MONO_PATCH_INFO_METHOD) ||
2529 (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) ||
2530 (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) ||
2531 (patch_info->type == MONO_PATCH_INFO_WRAPPER) ||
2532 (patch_info->type == MONO_PATCH_INFO_CLASS_INIT)) {
2533 /* Calls are made through the PLT */
2534 patch_info->type = MONO_PATCH_INFO_NONE;
2542 g_assert (cfg->has_got_slots);
2544 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2546 acfg->stats.info_size += p - buf;
2548 /* Emit method info */
2550 emit_label (acfg, symbol);
2553 g_assert (p - buf < buf_size);
2554 emit_bytes (acfg, buf, p - buf);
2559 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2562 int k, buf_size, method_index;
2563 guint32 debug_info_size;
2566 MonoMethodHeader *header;
2567 guint8 *p, *buf, *debug_info;
2569 method = cfg->method;
2570 code = cfg->native_code;
2571 header = mono_method_get_header (method);
2573 method_index = get_method_index (acfg, method);
2575 /* Make the labels local */
2576 symbol = g_strdup_printf (".Le_%x_p", method_index);
2578 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2580 buf_size = header->num_clauses * 256 + debug_info_size + 128;
2581 p = buf = g_malloc (buf_size);
2583 encode_value (cfg->code_len, p, &p);
2584 encode_value (cfg->used_int_regs, p, &p);
2586 /* Exception table */
2587 if (header->num_clauses) {
2588 MonoJitInfo *jinfo = cfg->jit_info;
2590 for (k = 0; k < header->num_clauses; ++k) {
2591 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2593 encode_value (ei->exvar_offset, p, &p);
2595 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2596 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2598 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2599 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2600 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2604 g_assert (debug_info_size < buf_size);
2606 encode_value (debug_info_size, p, &p);
2607 if (debug_info_size) {
2608 memcpy (p, debug_info, debug_info_size);
2609 p += debug_info_size;
2610 g_free (debug_info);
2613 acfg->stats.ex_info_size += p - buf;
2617 emit_label (acfg, symbol);
2620 g_assert (p - buf < buf_size);
2621 emit_bytes (acfg, buf, p - buf);
2626 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2628 MonoClass *klass = mono_class_get (acfg->image, token);
2632 gboolean no_special_static, cant_encode;
2634 buf_size = 10240 + (klass->vtable_size * 16);
2635 p = buf = g_malloc (buf_size);
2639 mono_class_init (klass);
2641 mono_class_setup_vtable (klass);
2644 * Emit all the information which is required for creating vtables so
2645 * the runtime does not need to create the MonoMethod structures which
2646 * take up a lot of space.
2649 no_special_static = !mono_class_has_special_static_fields (klass);
2651 /* Check whenever we have enough info to encode the vtable */
2652 cant_encode = FALSE;
2653 for (i = 0; i < klass->vtable_size; ++i) {
2654 MonoMethod *cm = klass->vtable [i];
2656 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
2660 if (klass->generic_container || cant_encode) {
2661 encode_value (-1, p, &p);
2663 encode_value (klass->vtable_size, p, &p);
2664 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);
2665 if (klass->has_cctor)
2666 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2667 if (klass->has_finalize)
2668 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2670 encode_value (klass->instance_size, p, &p);
2671 encode_value (mono_class_data_size (klass), p, &p);
2672 encode_value (klass->packing_size, p, &p);
2673 encode_value (klass->min_align, p, &p);
2675 for (i = 0; i < klass->vtable_size; ++i) {
2676 MonoMethod *cm = klass->vtable [i];
2679 encode_method_ref (acfg, cm, p, &p);
2681 encode_value (0, p, &p);
2685 acfg->stats.class_info_size += p - buf;
2688 symbol = g_strdup_printf (".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2689 emit_label (acfg, symbol);
2692 g_assert (p - buf < buf_size);
2693 emit_bytes (acfg, buf, p - buf);
2698 * Calls made from AOTed code are routed through a table of jumps similar to the
2699 * ELF PLT (Program Linkage Table). The differences are the following:
2700 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2701 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2702 * jumps. This means the jumps need to be patched when the address of the callee is
2703 * known. Initially the PLT entries jump to code which transfers control to the
2704 * AOT runtime through the first PLT entry.
2707 emit_plt (MonoAotCompile *acfg)
2712 guint32 *plt_info_offsets;
2715 * Encode info need to resolve PLT entries.
2717 buf_size = acfg->plt_offset * 128;
2718 p = buf = g_malloc (buf_size);
2720 plt_info_offsets = g_new0 (guint32, acfg->plt_offset);
2722 for (i = 1; i < acfg->plt_offset; ++i) {
2723 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
2725 plt_info_offsets [i] = p - buf;
2726 encode_value (patch_info->type, p, &p);
2727 encode_patch (acfg, patch_info, p, &p, FALSE);
2731 symbol = g_strdup_printf ("plt");
2733 /* This section will be made read-write by the AOT loader */
2734 emit_section_change (acfg, ".text", 0);
2735 emit_global (acfg, symbol, TRUE);
2736 emit_alignment (acfg, PAGESIZE);
2737 emit_label (acfg, symbol);
2740 #if defined(USE_BIN_WRITER) && defined(__arm__)
2742 g_assert_not_reached ();
2745 for (i = 0; i < acfg->plt_offset; ++i) {
2748 label = g_strdup_printf (".Lp_%d", i);
2749 emit_label (acfg, label);
2753 * The first plt entry is used to transfer code to the AOT loader.
2756 #if defined(__i386__)
2758 /* It is filled up during loading by the AOT loader. */
2759 emit_zero_bytes (acfg, 16);
2761 /* Need to make sure this is 9 bytes long */
2762 emit_byte (acfg, '\xe9');
2763 emit_symbol_diff (acfg, "plt", ".", -4);
2764 emit_int32 (acfg, plt_info_offsets [i]);
2766 #elif defined(__x86_64__)
2768 * We can't emit jumps because they are 32 bits only so they can't be patched.
2769 * So we emit a jump table instead whose entries are patched by the AOT loader to
2770 * point to .Lpd entries. ELF stores these in the GOT too, but we don't, since
2771 * methods with GOT entries can't be called directly.
2772 * We also emit the default PLT code here since the PLT code will not be patched.
2773 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
2775 /* jmpq *<offset>(%rip) */
2776 emit_byte (acfg, '\xff');
2777 emit_byte (acfg, '\x25');
2778 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)) -4);
2779 /* Used by mono_aot_get_plt_info_offset */
2780 emit_int32 (acfg, plt_info_offsets [i]);
2781 #elif defined(__arm__)
2783 * - optimize OP_AOTCONST implementation
2784 * - optimize the PLT entries
2785 * - optimize SWITCH AOT implementation
2786 * - implement IMT support
2788 emit_unset_mode (acfg);
2789 fprintf (acfg->fp, "\tldr ip, [pc, #4]\n");
2790 fprintf (acfg->fp, "\tadd ip, pc, ip\n");
2791 fprintf (acfg->fp, "\tldr pc, [ip, #0]\n");
2792 emit_symbol_diff (acfg, "plt_jump_table", ".", 0);
2793 /* Used by mono_aot_get_plt_info_offset */
2794 fprintf (acfg->fp, "\n\t.word %d\n", plt_info_offsets [i]);
2796 g_assert_not_reached ();
2800 g_free (plt_info_offsets);
2802 symbol = g_strdup_printf ("plt_end");
2803 emit_global (acfg, symbol, TRUE);
2804 emit_label (acfg, symbol);
2808 symbol = g_strdup_printf ("plt_info");
2809 emit_global (acfg, symbol, FALSE);
2810 emit_label (acfg, symbol);
2813 g_assert (p - buf < buf_size);
2814 emit_bytes (acfg, buf, p - buf);
2817 symbol = g_strdup_printf ("plt_jump_table_addr");
2818 emit_section_change (acfg, ".data", 0);
2819 emit_global (acfg, symbol, FALSE);
2820 emit_alignment (acfg, 8);
2821 emit_label (acfg, symbol);
2822 emit_pointer (acfg, "plt_jump_table");
2825 symbol = g_strdup_printf ("plt_jump_table_size");
2826 emit_section_change (acfg, ".data", 0);
2827 emit_global (acfg, symbol, FALSE);
2828 emit_alignment (acfg, 8);
2829 emit_label (acfg, symbol);
2830 emit_symbol_diff (acfg, "plt_jump_table_end", "plt_jump_table", 0);
2833 /* Don't make this a global so accesses don't need relocations */
2834 symbol = g_strdup_printf ("plt_jump_table");
2835 emit_section_change (acfg, ".bss", 0);
2836 emit_label (acfg, symbol);
2839 #if defined(__x86_64__) || defined(__arm__)
2840 emit_zero_bytes (acfg, (int)(acfg->plt_offset * sizeof (gpointer)));
2843 symbol = g_strdup_printf ("plt_jump_table_end");
2844 emit_label (acfg, symbol);
2848 static G_GNUC_UNUSED void
2849 emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code,
2850 guint32 code_size, int got_offset, MonoJumpInfo *ji)
2854 MonoJumpInfo *patch_info;
2860 symbol = g_strdup_printf ("%s", name);
2862 emit_section_change (acfg, ".text", 0);
2863 emit_global (acfg, symbol, TRUE);
2864 emit_alignment (acfg, 16);
2865 emit_label (acfg, symbol);
2869 * The code should access everything through the GOT, so we pass
2872 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
2876 /* Sort relocations */
2877 patches = g_ptr_array_new ();
2878 for (patch_info = ji; patch_info; patch_info = patch_info->next)
2879 g_ptr_array_add (patches, patch_info);
2880 g_ptr_array_sort (patches, compare_patches);
2882 buf_size = patches->len * 128 + 128;
2883 buf = g_malloc (buf_size);
2886 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
2887 g_assert (p - buf < buf_size);
2889 symbol = g_strdup_printf ("%s_p", name);
2891 emit_section_change (acfg, ".text", 0);
2892 emit_global (acfg, symbol, FALSE);
2893 emit_label (acfg, symbol);
2896 emit_bytes (acfg, buf, p - buf);
2900 * When running in aot-only mode, we can't create trampolines at runtime, so we create
2901 * a few, and save them in the AOT file. Normal trampolines embed their argument as a
2902 * literal inside the trampoline code, we can't do that here, so instead we embed an offset
2903 * which needs to be added to the trampoline address to get the address of the GOT slot
2904 * which contains the argument value.
2905 * The generated trampolines jump to the generic trampolines using another GOT slot, which
2906 * will be setup by the AOT loader to point to the generic trampoline code of the given
2910 emit_trampolines (MonoAotCompile *acfg)
2914 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2921 if (!acfg->aot_opts.full_aot)
2924 g_assert (acfg->image->assembly);
2926 /* Currently, we only most trampolines into the mscorlib AOT image. */
2927 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2928 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2930 * Emit the generic trampolines.
2932 * We could save some code by treating the generic trampolines as a wrapper
2933 * method, but that approach has its own complexities, so we choose the simpler
2936 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
2937 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, TRUE);
2939 /* Emit trampoline code */
2941 symbol = g_strdup_printf ("generic_trampoline_%d", tramp_type);
2943 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
2948 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
2949 emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL);
2951 /* Emit the exception related code pieces */
2952 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
2953 emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji);
2954 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
2955 emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji);
2956 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
2957 emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji);
2958 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
2959 emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji);
2960 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
2961 emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji);
2962 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
2963 emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji);
2967 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
2971 /* Reserve some entries at the end of the GOT for our use */
2972 acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
2974 symbol = g_strdup_printf ("trampolines");
2976 emit_section_change (acfg, ".text", 0);
2977 emit_global (acfg, symbol, TRUE);
2978 emit_alignment (acfg, 16);
2979 emit_label (acfg, symbol);
2981 for (i = 0; i < acfg->num_aot_trampolines; ++i) {
2982 offset = acfg->got_offset + (i * 2);
2985 * The trampolines created here are variations of the specific
2986 * trampolines created in mono_arch_create_specific_trampoline (). The
2988 * - the generic trampoline address is taken from a got slot.
2989 * - the offset of the got slot where the trampoline argument is stored
2990 * is embedded in the instruction stream, and the generic trampoline
2991 * can load the argument by loading the offset, adding it to the
2992 * address of the trampoline to get the address of the got slot, and
2993 * loading the argument from the there.
2995 #if defined(__x86_64__)
2996 /* This should be exactly 16 bytes long */
2997 /* It should work together with the generic trampoline code in tramp-amd64.c */
2998 /* call *<offset>(%rip) */
2999 emit_byte (acfg, '\x41');
3000 emit_byte (acfg, '\xff');
3001 emit_byte (acfg, '\x15');
3002 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
3003 /* This should be relative to the start of the trampoline */
3004 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
3005 emit_zero_bytes (acfg, 5);
3006 #elif defined(__arm__)
3010 /* Generate the trampoline code */
3011 /* This should be exactly 28 bytes long */
3014 ARM_PUSH (code, 0x5fff);
3015 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
3016 /* Load the value from the GOT */
3017 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
3019 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
3020 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
3022 g_assert (code - buf == 20);
3025 emit_bytes (acfg, buf, code - buf);
3026 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
3027 emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
3030 g_assert_not_reached ();
3035 /* Unbox trampolines */
3037 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3039 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3043 method = mono_get_method (acfg->image, token, NULL);
3045 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3046 if (!cfg || !cfg->method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
3049 symbol = g_strdup_printf ("unbox_trampoline_%d", i);
3051 emit_section_change (acfg, ".text", 0);
3052 emit_global (acfg, symbol, TRUE);
3053 emit_label (acfg, symbol);
3055 call_target = g_strdup_printf (".Lm_%x", get_method_index (acfg, cfg->method));
3057 #if defined(__x86_64__)
3062 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (cfg->method), cfg->generic_sharing_context, NULL);
3064 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
3066 emit_bytes (acfg, buf, code - buf);
3068 emit_byte (acfg, '\xe9');
3069 emit_symbol_diff (acfg, call_target, ".", -4);
3071 #elif defined(__arm__)
3078 if (MONO_TYPE_ISSTRUCT (mono_method_signature (cfg->method)->ret))
3081 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
3083 emit_bytes (acfg, buf, code - buf);
3084 /* jump to method */
3085 #if defined(USE_BIN_WRITER)
3087 g_assert_not_reached ();
3089 fprintf (acfg->fp, "\n\tb %s\n", call_target);
3092 g_assert_not_reached ();
3096 symbol = g_strdup_printf ("trampolines_info");
3098 emit_section_change (acfg, ".text", 0);
3099 emit_global (acfg, symbol, TRUE);
3100 emit_alignment (acfg, PAGESIZE);
3101 emit_label (acfg, symbol);
3103 emit_int32 (acfg, acfg->num_aot_trampolines);
3104 emit_int32 (acfg, acfg->got_offset);
3108 str_begins_with (const char *str1, const char *str2)
3110 int len = strlen (str2);
3111 return strncmp (str1, str2, len) == 0;
3115 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3117 gchar **args, **ptr;
3119 memset (opts, 0, sizeof (*opts));
3121 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3122 for (ptr = args; ptr && *ptr; ptr ++) {
3123 const char *arg = *ptr;
3125 if (str_begins_with (arg, "outfile=")) {
3126 opts->outfile = g_strdup (arg + strlen ("outfile="));
3127 } else if (str_begins_with (arg, "save-temps")) {
3128 opts->save_temps = TRUE;
3129 } else if (str_begins_with (arg, "keep-temps")) {
3130 opts->save_temps = TRUE;
3131 } else if (str_begins_with (arg, "write-symbols")) {
3132 opts->write_symbols = TRUE;
3133 } else if (str_begins_with (arg, "metadata-only")) {
3134 opts->metadata_only = TRUE;
3135 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3136 opts->bind_to_runtime_version = TRUE;
3137 } else if (str_begins_with (arg, "full")) {
3138 opts->full_aot = TRUE;
3139 } else if (str_begins_with (arg, "no-dlsym")) {
3140 opts->no_dlsym = TRUE;
3142 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3151 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3153 MonoMethod *method = (MonoMethod*)key;
3154 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3155 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3156 MonoAotCompile *acfg = user_data;
3158 new_ji->image = ji->image;
3159 new_ji->token = ji->token;
3160 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3164 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3167 MonoJumpInfo *patch_info;
3171 if (acfg->aot_opts.metadata_only)
3174 index = get_method_index (acfg, method);
3176 /* fixme: maybe we can also precompile wrapper methods */
3177 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3178 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3179 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3180 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3184 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3187 acfg->stats.mcount++;
3189 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3191 * FIXME: Enabling this causes virtual-sync.exe to fail, since the trampoline
3192 * code can't determine that it needs to insert a sync wrapper in the AOT case.
3197 //acfg->opts &= ~MONO_OPT_GSHARED;
3199 // FIXME: GSHARED is on by default
3200 if (TRUE || !(acfg->opts & MONO_OPT_GSHARED)) {
3201 if (method->is_generic || method->klass->generic_container) {
3202 acfg->stats.genericcount ++;
3207 if (acfg->aot_opts.full_aot)
3208 mono_use_imt = FALSE;
3211 * Since these methods are the only ones which are compiled with
3212 * AOT support, and they are not used by runtime startup/shutdown code,
3213 * the runtime will not see AOT methods during AOT compilation,so it
3214 * does not need to support them by creating a fake GOT etc.
3216 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3217 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3218 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3219 acfg->stats.genericcount ++;
3222 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3223 /* Let the exception happen at runtime */
3227 if (cfg->disable_aot) {
3228 //printf ("Skip (other): %s\n", mono_method_full_name (method, TRUE));
3229 acfg->stats.ocount++;
3230 mono_destroy_compile (cfg);
3234 /* Nullify patches which need no aot processing */
3235 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3236 switch (patch_info->type) {
3237 case MONO_PATCH_INFO_LABEL:
3238 case MONO_PATCH_INFO_BB:
3239 patch_info->type = MONO_PATCH_INFO_NONE;
3246 /* Collect method->token associations from the cfg */
3247 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3250 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3251 switch (patch_info->type) {
3252 case MONO_PATCH_INFO_ABS:
3253 /* unable to handle this */
3254 //printf ("Skip (abs addr): %s %d\n", mono_method_full_name (method, TRUE), patch_info->type);
3263 acfg->stats.abscount++;
3264 mono_destroy_compile (cfg);
3269 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3270 if (patch_info->type == MONO_PATCH_INFO_METHOD_JUMP) {
3272 * FIXME: We can't handle this because mono_jit_compile_method_inner will try
3273 * to patch the AOT code when the target of the jump is compiled.
3281 acfg->stats.ocount++;
3282 mono_destroy_compile (cfg);
3286 /* some wrappers are very common */
3287 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3288 if (patch_info->type == MONO_PATCH_INFO_METHODCONST) {
3289 switch (patch_info->data.method->wrapper_type) {
3290 case MONO_WRAPPER_PROXY_ISINST:
3291 patch_info->type = MONO_PATCH_INFO_WRAPPER;
3295 if (patch_info->type == MONO_PATCH_INFO_METHOD) {
3296 switch (patch_info->data.method->wrapper_type) {
3297 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3298 case MONO_WRAPPER_XDOMAIN_INVOKE:
3299 case MONO_WRAPPER_STFLD:
3300 case MONO_WRAPPER_LDFLD:
3301 case MONO_WRAPPER_LDFLDA:
3302 case MONO_WRAPPER_LDFLD_REMOTE:
3303 case MONO_WRAPPER_STFLD_REMOTE:
3304 case MONO_WRAPPER_STELEMREF:
3305 case MONO_WRAPPER_ISINST:
3306 case MONO_WRAPPER_PROXY_ISINST:
3307 case MONO_WRAPPER_ALLOC:
3308 case MONO_WRAPPER_REMOTING_INVOKE:
3309 patch_info->type = MONO_PATCH_INFO_WRAPPER;
3316 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3317 switch (patch_info->type) {
3318 case MONO_PATCH_INFO_METHOD:
3319 case MONO_PATCH_INFO_METHODCONST:
3320 if (patch_info->data.method->wrapper_type) {
3321 /* unable to handle this */
3322 //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));
3326 if (!patch_info->data.method->token) {
3327 /* The method is part of a constructed type like Int[,].Set (). */
3328 if (!g_hash_table_lookup (acfg->token_info_hash, patch_info->data.method))
3331 if (patch_info->data.method->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, patch_info->data.method))
3332 /* FIXME: Can't encode these */
3335 case MONO_PATCH_INFO_VTABLE:
3336 case MONO_PATCH_INFO_CLASS_INIT:
3337 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3338 case MONO_PATCH_INFO_CLASS:
3339 case MONO_PATCH_INFO_IID:
3340 case MONO_PATCH_INFO_ADJUSTED_IID:
3341 if (!patch_info->data.klass->type_token)
3342 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))
3351 acfg->stats.wrappercount++;
3352 mono_destroy_compile (cfg);
3356 /* Determine whenever the method has GOT slots */
3357 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3358 switch (patch_info->type) {
3359 case MONO_PATCH_INFO_GOT_OFFSET:
3360 case MONO_PATCH_INFO_NONE:
3361 case MONO_PATCH_INFO_METHOD:
3362 case MONO_PATCH_INFO_INTERNAL_METHOD:
3363 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3364 case MONO_PATCH_INFO_WRAPPER:
3366 case MONO_PATCH_INFO_IMAGE:
3367 if (patch_info->data.image == acfg->image)
3368 /* Stored in GOT slot 0 */
3372 cfg->has_got_slots = TRUE;
3377 if (!cfg->has_got_slots)
3378 acfg->stats.methods_without_got_slots ++;
3380 /* Make a copy of the patch info which is in the mempool */
3382 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3384 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3385 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3388 patches = new_patch_info;
3390 patches_end->next = new_patch_info;
3391 patches_end = new_patch_info;
3393 cfg->patch_info = patches;
3396 /* Free some fields used by cfg to conserve memory */
3397 mono_mempool_destroy (cfg->mempool);
3398 cfg->mempool = NULL;
3399 g_free (cfg->varinfo);
3400 cfg->varinfo = NULL;
3404 mono_regstate_free (cfg->rs);
3408 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
3410 acfg->cfgs [index] = cfg;
3412 g_hash_table_insert (acfg->method_to_cfg, cfg->method, cfg);
3414 acfg->stats.ccount++;
3418 load_profile_files (MonoAotCompile *acfg)
3422 int file_index, res, method_index, i;
3429 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);
3431 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3436 infile = fopen (tmp, "r");
3439 printf ("Using profile data file '%s'\n", tmp);
3444 res = fscanf (infile, "%32s\n", ver);
3445 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3446 printf ("Profile file has wrong version or invalid.\n");
3452 res = fscanf (infile, "%d\n", &token);
3456 method_index = mono_metadata_token_index (token) - 1;
3458 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3459 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3464 /* Add missing methods */
3466 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3467 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3468 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3470 unordered = g_list_reverse (unordered);
3471 if (acfg->method_order)
3472 g_list_last (acfg->method_order)->next = unordered;
3474 acfg->method_order = unordered;
3480 * Collect all patches which have shared GOT entries and alloc entries for them. The
3481 * rest will get entries allocated during emit_code ().
3484 alloc_got_slots (MonoAotCompile *acfg)
3490 /* Slot 0 is reserved for the address of the current assembly */
3491 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3492 ji->type = MONO_PATCH_INFO_IMAGE;
3493 ji->data.image = acfg->image;
3495 get_shared_got_offset (acfg, ji);
3497 for (l = acfg->method_order; l != NULL; l = l->next) {
3498 i = GPOINTER_TO_UINT (l->data);
3500 if (acfg->cfgs [i]) {
3501 MonoCompile *cfg = acfg->cfgs [i];
3503 for (ji = cfg->patch_info; ji; ji = ji->next) {
3505 case MONO_PATCH_INFO_VTABLE:
3506 case MONO_PATCH_INFO_CLASS:
3507 case MONO_PATCH_INFO_IID:
3508 case MONO_PATCH_INFO_ADJUSTED_IID:
3509 case MONO_PATCH_INFO_FIELD:
3510 case MONO_PATCH_INFO_SFLDA:
3511 case MONO_PATCH_INFO_DECLSEC:
3512 case MONO_PATCH_INFO_LDTOKEN:
3513 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3514 case MONO_PATCH_INFO_RVA:
3515 get_shared_got_offset (acfg, ji);
3526 emit_code (MonoAotCompile *acfg)
3532 symbol = g_strdup_printf ("methods");
3533 emit_section_change (acfg, ".text", 0);
3534 emit_global (acfg, symbol, TRUE);
3535 emit_alignment (acfg, 8);
3536 emit_label (acfg, symbol);
3539 for (l = acfg->method_order; l != NULL; l = l->next) {
3540 i = GPOINTER_TO_UINT (l->data);
3543 emit_method_code (acfg, acfg->cfgs [i]);
3546 symbol = g_strdup_printf ("methods_end");
3547 emit_section_change (acfg, ".text", 0);
3548 emit_global (acfg, symbol, FALSE);
3549 emit_alignment (acfg, 8);
3550 emit_label (acfg, symbol);
3553 symbol = g_strdup_printf ("method_offsets");
3554 emit_section_change (acfg, ".text", 1);
3555 emit_global (acfg, symbol, FALSE);
3556 emit_alignment (acfg, 8);
3557 emit_label (acfg, symbol);
3560 for (i = 0; i < acfg->nmethods; ++i) {
3561 if (acfg->cfgs [i]) {
3562 symbol = g_strdup_printf (".Lm_%x", i);
3563 emit_symbol_diff (acfg, symbol, "methods", 0);
3566 emit_int32 (acfg, 0xffffffff);
3573 emit_info (MonoAotCompile *acfg)
3579 /* Emit method info */
3580 symbol = g_strdup_printf ("method_info");
3581 emit_section_change (acfg, ".text", 1);
3582 emit_global (acfg, symbol, FALSE);
3583 emit_alignment (acfg, 8);
3584 emit_label (acfg, symbol);
3587 /* To reduce size of generated assembly code */
3588 symbol = g_strdup_printf ("mi");
3589 emit_label (acfg, symbol);
3592 for (l = acfg->method_order; l != NULL; l = l->next) {
3593 i = GPOINTER_TO_UINT (l->data);
3596 emit_method_info (acfg, acfg->cfgs [i]);
3599 symbol = g_strdup_printf ("method_info_offsets");
3600 emit_section_change (acfg, ".text", 1);
3601 emit_global (acfg, symbol, FALSE);
3602 emit_alignment (acfg, 8);
3603 emit_label (acfg, symbol);
3606 for (i = 0; i < acfg->nmethods; ++i) {
3607 if (acfg->cfgs [i]) {
3608 symbol = g_strdup_printf (".Lm_%x_p", i);
3609 emit_symbol_diff (acfg, symbol, "mi", 0);
3612 emit_int32 (acfg, 0);
3619 emit_wrapper_info (MonoAotCompile *acfg)
3625 /* Emit method info */
3626 symbol = g_strdup_printf ("wrapper_info");
3627 emit_section_change (acfg, ".text", 1);
3628 emit_global (acfg, symbol, FALSE);
3629 emit_alignment (acfg, 8);
3630 emit_label (acfg, symbol);
3633 if (!acfg->aot_opts.full_aot)
3636 for (i = 0; i < acfg->nmethods; ++i) {
3637 MonoCompile *cfg = acfg->cfgs [i];
3639 if (!cfg || !cfg->method->wrapper_type)
3642 index = get_method_index (acfg, cfg->method);
3644 // FIXME: Optimize disk usage and lookup speed
3645 name = mono_method_full_name (cfg->method, TRUE);
3646 emit_string (acfg, name);
3647 emit_alignment (acfg, 4);
3648 emit_int32 (acfg, index);
3651 emit_byte (acfg, 0);
3657 emit_method_order (MonoAotCompile *acfg)
3663 symbol = g_strdup_printf ("method_order");
3664 emit_section_change (acfg, ".text", 1);
3665 emit_global (acfg, symbol, FALSE);
3666 emit_alignment (acfg, 8);
3667 emit_label (acfg, symbol);
3670 /* First emit an index table */
3673 for (l = acfg->method_order; l != NULL; l = l->next) {
3674 i = GPOINTER_TO_UINT (l->data);
3676 if (acfg->cfgs [i]) {
3677 if ((index % 1024) == 0) {
3678 emit_int32 (acfg, i);
3686 emit_int32 (acfg, 0xffffff);
3688 /* Then emit the whole method order */
3689 for (l = acfg->method_order; l != NULL; l = l->next) {
3690 i = GPOINTER_TO_UINT (l->data);
3692 if (acfg->cfgs [i]) {
3693 emit_int32 (acfg, i);
3698 symbol = g_strdup_printf ("method_order_end");
3699 emit_section_change (acfg, ".text", 1);
3700 emit_global (acfg, symbol, FALSE);
3701 emit_label (acfg, symbol);
3706 emit_exception_info (MonoAotCompile *acfg)
3711 symbol = g_strdup_printf ("ex_info");
3712 emit_section_change (acfg, ".text", 1);
3713 emit_global (acfg, symbol, FALSE);
3714 emit_alignment (acfg, 8);
3715 emit_label (acfg, symbol);
3718 /* To reduce size of generated assembly */
3719 symbol = g_strdup_printf ("ex");
3720 emit_label (acfg, symbol);
3723 for (i = 0; i < acfg->nmethods; ++i) {
3725 emit_exception_debug_info (acfg, acfg->cfgs [i]);
3728 symbol = g_strdup_printf ("ex_info_offsets");
3729 emit_section_change (acfg, ".text", 1);
3730 emit_global (acfg, symbol, FALSE);
3731 emit_alignment (acfg, 8);
3732 emit_label (acfg, symbol);
3735 for (i = 0; i < acfg->nmethods; ++i) {
3736 if (acfg->cfgs [i]) {
3737 symbol = g_strdup_printf (".Le_%x_p", i);
3738 emit_symbol_diff (acfg, symbol, "ex", 0);
3741 emit_int32 (acfg, 0);
3748 emit_class_info (MonoAotCompile *acfg)
3753 symbol = g_strdup_printf ("class_info");
3754 emit_section_change (acfg, ".text", 1);
3755 emit_global (acfg, symbol, FALSE);
3756 emit_alignment (acfg, 8);
3757 emit_label (acfg, symbol);
3760 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
3761 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
3763 symbol = g_strdup_printf ("class_info_offsets");
3764 emit_section_change (acfg, ".text", 1);
3765 emit_global (acfg, symbol, FALSE);
3766 emit_alignment (acfg, 8);
3767 emit_label (acfg, symbol);
3770 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3771 symbol = g_strdup_printf (".LK_I_%x", i);
3772 emit_symbol_diff (acfg, symbol, "class_info", 0);
3778 typedef struct ClassNameTableEntry {
3779 guint32 token, index;
3780 struct ClassNameTableEntry *next;
3781 } ClassNameTableEntry;
3784 emit_class_name_table (MonoAotCompile *acfg)
3787 guint32 token, hash;
3792 ClassNameTableEntry *entry, *new_entry;
3795 * Construct a chained hash table for mapping class names to typedef tokens.
3797 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
3798 table = g_ptr_array_sized_new (table_size);
3799 for (i = 0; i < table_size; ++i)
3800 g_ptr_array_add (table, NULL);
3801 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3802 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3803 klass = mono_class_get (acfg->image, token);
3804 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
3805 hash = g_str_hash (full_name) % table_size;
3808 /* FIXME: Allocate from the mempool */
3809 new_entry = g_new0 (ClassNameTableEntry, 1);
3810 new_entry->token = token;
3812 entry = g_ptr_array_index (table, hash);
3813 if (entry == NULL) {
3814 new_entry->index = hash;
3815 g_ptr_array_index (table, hash) = new_entry;
3818 entry = entry->next;
3820 entry->next = new_entry;
3821 new_entry->index = table->len;
3822 g_ptr_array_add (table, new_entry);
3826 /* Emit the table */
3827 symbol = g_strdup_printf ("class_name_table");
3828 emit_section_change (acfg, ".text", 0);
3829 emit_global (acfg, symbol, FALSE);
3830 emit_alignment (acfg, 8);
3831 emit_label (acfg, symbol);
3834 /* FIXME: Optimize memory usage */
3835 g_assert (table_size < 65000);
3836 emit_int16 (acfg, table_size);
3837 g_assert (table->len < 65000);
3838 for (i = 0; i < table->len; ++i) {
3839 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
3841 if (entry == NULL) {
3842 emit_int16 (acfg, 0);
3843 emit_int16 (acfg, 0);
3845 emit_int16 (acfg, mono_metadata_token_index (entry->token));
3847 emit_int16 (acfg, entry->next->index);
3849 emit_int16 (acfg, 0);
3855 emit_image_table (MonoAotCompile *acfg)
3861 * The image table is small but referenced in a lot of places.
3862 * So we emit it at once, and reference its elements by an index.
3865 symbol = g_strdup_printf ("mono_image_table");
3866 emit_section_change (acfg, ".text", 1);
3867 emit_global (acfg, symbol, FALSE);
3868 emit_alignment (acfg, 8);
3869 emit_label (acfg, symbol);
3872 emit_int32 (acfg, acfg->image_table->len);
3873 for (i = 0; i < acfg->image_table->len; i++) {
3874 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
3875 MonoAssemblyName *aname = &image->assembly->aname;
3877 /* FIXME: Support multi-module assemblies */
3878 g_assert (image->assembly->image == image);
3880 emit_string (acfg, image->assembly_name);
3881 emit_string (acfg, image->guid);
3882 emit_string (acfg, aname->culture ? aname->culture : "");
3883 emit_string (acfg, (const char*)aname->public_key_token);
3885 emit_alignment (acfg, 8);
3886 emit_int32 (acfg, aname->flags);
3887 emit_int32 (acfg, aname->major);
3888 emit_int32 (acfg, aname->minor);
3889 emit_int32 (acfg, aname->build);
3890 emit_int32 (acfg, aname->revision);
3895 emit_got_info (MonoAotCompile *acfg)
3900 guint32 *got_info_offsets;
3904 * - optimize offsets table.
3905 * - reduce number of exported symbols.
3906 * - emit info for a klass only once.
3907 * - determine when a method uses a GOT slot which is guaranteed to be already
3909 * - clean up and document the code.
3910 * - use String.Empty in class libs.
3913 /* Encode info required to decode shared GOT entries */
3914 buf_size = acfg->shared_patches->len * 64;
3915 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
3916 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
3917 for (i = 0; i < acfg->shared_patches->len; ++i) {
3918 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
3920 /* No need to encode the patch type */
3921 got_info_offsets [i] = p - buf;
3922 encode_patch (acfg, ji, p, &p, FALSE);
3925 g_assert (p - buf <= buf_size);
3927 acfg->stats.got_info_size = p - buf;
3929 /* Emit got_info table */
3930 symbol = g_strdup_printf ("got_info");
3931 emit_section_change (acfg, ".text", 1);
3932 emit_global (acfg, symbol, FALSE);
3933 emit_alignment (acfg, 8);
3934 emit_label (acfg, symbol);
3937 emit_bytes (acfg, buf, p - buf);
3939 /* Emit got_info_offsets table */
3940 symbol = g_strdup_printf ("got_info_offsets");
3941 emit_section_change (acfg, ".text", 1);
3942 emit_global (acfg, symbol, FALSE);
3943 emit_alignment (acfg, 8);
3944 emit_label (acfg, symbol);
3947 for (i = 0; i < acfg->shared_patches->len; ++i)
3948 emit_int32 (acfg, got_info_offsets [i]);
3950 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
3954 emit_got (MonoAotCompile *acfg)
3958 /* Don't make GOT global so accesses to it don't need relocations */
3959 symbol = g_strdup_printf ("got");
3960 emit_section_change (acfg, ".bss", 1);
3961 emit_alignment (acfg, 8);
3962 emit_label (acfg, symbol);
3963 if ((acfg->got_offset + acfg->num_trampoline_got_entries) > 0)
3964 emit_zero_bytes (acfg, (int)((acfg->got_offset + acfg->num_trampoline_got_entries) * sizeof (gpointer)));
3967 symbol = g_strdup_printf ("got_addr");
3968 emit_section_change (acfg, ".data", 1);
3969 emit_global (acfg, symbol, FALSE);
3970 emit_alignment (acfg, 8);
3971 emit_label (acfg, symbol);
3972 emit_pointer (acfg, "got");
3975 symbol = g_strdup_printf ("got_size");
3976 emit_section_change (acfg, ".data", 1);
3977 emit_global (acfg, symbol, FALSE);
3978 emit_alignment (acfg, 8);
3979 emit_label (acfg, symbol);
3980 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
3985 emit_globals (MonoAotCompile *acfg)
3989 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
3991 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
3993 opts_str = g_strdup_printf ("%d", acfg->opts);
3994 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
3997 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
3999 if (acfg->aot_opts.bind_to_runtime_version)
4000 emit_string_symbol (acfg, "mono_runtime_version", FULL_VERSION);
4002 emit_string_symbol (acfg, "mono_runtime_version", "");
4005 * Some platforms like the iphone have no working dlsym (). To work around this,
4006 * we create an ELF ctor function which will be invoked by dlopen, and which
4007 * will call a function in the AOT loader to register the symbols used by the
4010 if (acfg->aot_opts.no_dlsym) {
4014 /* Emit the names */
4015 for (i = 0; i < acfg->globals->len; ++i) {
4016 char *name = g_ptr_array_index (acfg->globals, i);
4018 symbol = g_strdup_printf ("name_%d", i);
4019 emit_section_change (acfg, ".text", 1);
4020 emit_label (acfg, symbol);
4021 emit_string (acfg, name);
4025 /* Emit the globals table */
4026 symbol = g_strdup_printf ("globals");
4027 emit_section_change (acfg, ".data", 0);
4028 /* This is not a global, since it is accessed by the init function */
4029 emit_alignment (acfg, 8);
4030 emit_label (acfg, symbol);
4032 for (i = 0; i < acfg->globals->len; ++i) {
4033 char *name = g_ptr_array_index (acfg->globals, i);
4035 symbol = g_strdup_printf ("name_%d", i);
4036 emit_pointer (acfg, symbol);
4039 symbol = g_strdup_printf ("%s", name);
4040 emit_pointer (acfg, symbol);
4043 /* Null terminate the table */
4044 emit_pointer (acfg, NULL);
4045 emit_pointer (acfg, NULL);
4047 symbol = g_strdup_printf ("init_%s", acfg->image->assembly->aname.name);
4048 emit_section_change (acfg, ".text", 1);
4049 emit_alignment (acfg, 8);
4050 emit_label (acfg, symbol);
4051 #ifdef USE_BIN_WRITER
4052 g_assert_not_reached ();
4055 fprintf (acfg->fp, "leaq globals(%%rip), %%rdi\n");
4056 fprintf (acfg->fp, "call mono_aot_register_globals@PLT\n");
4057 fprintf (acfg->fp, "ret\n");
4058 fprintf (acfg->fp, ".section .ctors,\"aw\",@progbits\n");
4059 emit_alignment (acfg, 8);
4060 emit_pointer (acfg, symbol);
4061 #elif defined(__arm__)
4063 * Taken from gcc generated code for:
4065 * void foo () { bar (&i); }
4066 * gcc --shared -fPIC -O2
4068 fprintf (acfg->fp, "ldr r3, .L5\n");
4069 fprintf (acfg->fp, "ldr r0, .L5+4\n");
4070 fprintf (acfg->fp, ".LPIC0:\n");
4071 fprintf (acfg->fp, "add r3, pc, r3\n");
4072 fprintf (acfg->fp, "add r0, r3, r0\n");
4073 fprintf (acfg->fp, "b mono_aot_register_globals(PLT)\n");
4075 fprintf (acfg->fp, ".L5:\n");
4076 fprintf (acfg->fp, ".word _GLOBAL_OFFSET_TABLE_-(.LPIC0+8)\n");
4077 fprintf (acfg->fp, ".word globals(GOTOFF)\n");
4079 fprintf (acfg->fp, ".section .init_array,\"aw\",%%init_array\n");
4080 fprintf (acfg->fp, ".align 2\n");
4081 fprintf (acfg->fp, ".word %s(target1)\n", symbol);
4083 g_assert_not_reached ();
4091 acfg_free (MonoAotCompile *acfg)
4095 for (i = 0; i < acfg->nmethods; ++i)
4097 g_free (acfg->cfgs [i]);
4098 g_free (acfg->cfgs);
4099 g_free (acfg->method_got_offsets);
4100 g_free (acfg->patch_to_plt_offset_wrapper);
4101 g_ptr_array_free (acfg->methods, TRUE);
4102 g_ptr_array_free (acfg->shared_patches, TRUE);
4103 g_ptr_array_free (acfg->image_table, TRUE);
4104 g_ptr_array_free (acfg->globals, TRUE);
4105 g_hash_table_destroy (acfg->method_indexes);
4106 g_hash_table_destroy (acfg->plt_offset_to_patch);
4107 g_hash_table_destroy (acfg->patch_to_plt_offset);
4108 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
4109 g_hash_table_destroy (acfg->method_to_cfg);
4110 g_hash_table_destroy (acfg->token_info_hash);
4111 g_hash_table_destroy (acfg->image_hash);
4112 mono_mempool_destroy (acfg->mempool);
4118 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4120 MonoImage *image = ass->image;
4123 MonoAotCompile *acfg;
4125 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4127 acfg = g_new0 (MonoAotCompile, 1);
4128 acfg->methods = g_ptr_array_new ();
4129 acfg->method_indexes = g_hash_table_new (NULL, NULL);
4130 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4131 acfg->patch_to_plt_offset = g_hash_table_new (NULL, NULL);
4132 acfg->patch_to_plt_offset_wrapper = g_malloc0 (sizeof (GHashTable*) * 128);
4133 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4134 acfg->shared_patches = g_ptr_array_new ();
4135 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4136 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4137 acfg->image_hash = g_hash_table_new (NULL, NULL);
4138 acfg->image_table = g_ptr_array_new ();
4139 acfg->globals = g_ptr_array_new ();
4140 acfg->image = image;
4142 acfg->mempool = mono_mempool_new ();
4144 mono_aot_parse_options (aot_options, &acfg->aot_opts);
4146 load_profile_files (acfg);
4150 acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 10240 : 0;
4152 acfg->method_index = 1;
4154 /* Collect methods */
4155 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4157 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4159 method = mono_get_method (acfg->image, token, NULL);
4161 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4162 /* Compile the wrapper instead */
4163 /* We do this here instead of add_wrappers () because it is easy to do it here */
4164 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc);
4168 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4169 add_method_with_index (acfg, method, i);
4170 acfg->method_index ++;
4173 if (acfg->aot_opts.full_aot)
4174 add_wrappers (acfg);
4176 acfg->nmethods = acfg->methods->len;
4177 acfg->cfgs = g_new0 (MonoCompile*, acfg->nmethods + 32);
4178 acfg->method_got_offsets = g_new0 (guint32, acfg->nmethods + 32);
4180 /* PLT offset 0 is reserved for the PLT trampoline */
4181 acfg->plt_offset = 1;
4183 /* Compile methods */
4184 for (i = 0; i < acfg->methods->len; ++i) {
4185 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4188 alloc_got_slots (acfg);
4194 emit_wrapper_info (acfg);
4196 emit_method_order (acfg);
4198 emit_trampolines (acfg);
4200 emit_class_name_table (acfg);
4202 emit_got_info (acfg);
4204 emit_exception_info (acfg);
4206 emit_class_info (acfg);
4210 emit_image_table (acfg);
4214 emit_globals (acfg);
4216 symbol = g_strdup_printf ("mem_end");
4217 emit_section_change (acfg, ".text", 1);
4218 emit_global (acfg, symbol, FALSE);
4219 emit_alignment (acfg, 8);
4220 emit_label (acfg, symbol);
4223 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)));
4225 res = emit_writeout (acfg);
4231 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);
4232 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4233 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4234 printf ("%d methods contain wrapper references (%d%%)\n", acfg->stats.wrappercount, acfg->stats.mcount ? (acfg->stats.wrappercount * 100) / acfg->stats.mcount : 100);
4235 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4236 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4237 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);
4238 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4240 printf ("GOT slot distribution:\n");
4241 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4242 if (acfg->stats.got_slot_types [i])
4243 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4255 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)