2 * aot.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
11 /* Remaining AOT-only work:
12 * - reduce the length of the wrapper names.
13 * - aot IMT tables, so we don't have two kinds of aot code.
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
23 * - every shared method has a MonoGenericJitInfo structure which is only really
24 * used for handling catch clauses with open types, not a very common use case.
28 #include <sys/types.h>
35 #ifndef PLATFORM_WIN32
44 #include <limits.h> /* for PAGESIZE */
49 #include <mono/metadata/tabledefs.h>
50 #include <mono/metadata/class.h>
51 #include <mono/metadata/object.h>
52 #include <mono/metadata/tokentype.h>
53 #include <mono/metadata/appdomain.h>
54 #include <mono/metadata/debug-helpers.h>
55 #include <mono/metadata/assembly.h>
56 #include <mono/metadata/metadata-internals.h>
57 #include <mono/metadata/marshal.h>
58 #include <mono/metadata/gc-internal.h>
59 #include <mono/metadata/method-builder.h>
60 #include <mono/utils/mono-logger.h>
61 #include "mono/utils/mono-compiler.h"
69 #define SHARED_EXT ".dll"
70 #elif defined(__ppc__) && defined(__MACH__)
71 #define SHARED_EXT ".dylib"
73 #define SHARED_EXT ".so"
76 #if defined(sparc) || defined(__ppc__) || defined(__powerpc__) || defined(__MACH__)
77 #define AS_STRING_DIRECTIVE ".asciz"
80 #define AS_STRING_DIRECTIVE ".string"
85 // .byte generates 1 byte per expression.
86 // .short generates 2 bytes per expression.
87 // .long generates 4 bytes per expression.
88 // .quad generates 8 bytes per expression.
90 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
91 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
93 typedef struct MonoAotOptions {
96 gboolean write_symbols;
97 gboolean metadata_only;
98 gboolean bind_to_runtime_version;
101 gboolean static_link;
105 typedef struct MonoAotStats {
106 int ccount, mcount, lmfcount, abscount, wrappercount, gcount, ocount, genericcount;
107 int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
108 int methods_without_got_slots, direct_calls, all_calls;
110 int got_slot_types [MONO_PATCH_INFO_NONE];
113 /*#define USE_ELF_WRITER 1*/
115 #if defined(USE_ELF_WRITER)
116 #define USE_BIN_WRITER 1
119 #ifdef USE_BIN_WRITER
121 typedef struct _BinSymbol BinSymbol;
122 typedef struct _BinReloc BinReloc;
123 typedef struct _BinSection BinSection;
137 typedef struct MonoAotCompile {
140 GHashTable *method_indexes;
142 GHashTable *patch_to_plt_offset;
143 GHashTable *plt_offset_to_patch;
144 GHashTable *patch_to_shared_got_offset;
145 GPtrArray *shared_patches;
146 GHashTable *image_hash;
147 GHashTable *method_to_cfg;
148 GHashTable *token_info_hash;
149 GPtrArray *image_table;
152 /* Number of trampolines emitted into the AOT file */
153 guint32 num_aot_trampolines;
154 guint32 got_offset, plt_offset;
155 /* Number of GOT entries reserved for trampolines */
156 guint32 num_trampoline_got_entries;
157 guint32 *method_got_offsets;
158 MonoAotOptions aot_opts;
161 MonoMemPool *mempool;
164 char *static_linking_symbol;
165 #ifdef USE_BIN_WRITER
167 BinSection *sections;
168 BinSection *cur_section;
169 BinReloc *relocations;
175 int mode; /* emit mode */
176 int col_count; /* bytes emitted per .byte line */
180 #ifdef HAVE_ARRAY_ELEM_INIT
181 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
182 #define MSGSTRFIELD1(line) str##line
183 static const struct msgstr_t {
184 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
185 #include "patch-info.h"
188 #define PATCH_INFO(a,b) b,
189 #include "patch-info.h"
192 static const gint16 opidx [] = {
193 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
194 #include "patch-info.h"
199 get_patch_name (int info)
201 return (const char*)&opstr + opidx [info];
205 #define PATCH_INFO(a,b) b,
206 static const char* const
207 patch_types [MONO_PATCH_INFO_NUM + 1] = {
208 #include "patch-info.h"
213 get_patch_name (int info)
215 return patch_types [info];
221 emit_global (MonoAotCompile *acfg, const char *name, gboolean func);
224 is_got_patch (MonoJumpInfoType patch_type)
229 static G_GNUC_UNUSED int
230 ilog2(register int value)
233 while (value & ~0xf) count += 4, value >>= 4;
234 while (value) count++, value >>= 1;
238 #ifdef USE_BIN_WRITER
240 typedef struct _BinLabel BinLabel;
251 BinSection *val2_section;
263 gboolean is_function;
281 emit_start (MonoAotCompile *acfg)
283 acfg->labels = g_hash_table_new (g_str_hash, g_str_equal);
287 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
291 if (acfg->cur_section && acfg->cur_section->subsection == subsection_index
292 && strcmp (acfg->cur_section->name, section_name) == 0)
294 for (section = acfg->sections; section; section = section->next) {
295 if (section->subsection == subsection_index && strcmp (section->name, section_name) == 0) {
296 acfg->cur_section = section;
301 section = g_new0 (BinSection, 1);
302 section->name = g_strdup (section_name);
303 section->subsection = subsection_index;
304 section->next = acfg->sections;
305 acfg->sections = section;
306 acfg->cur_section = section;
311 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
313 BinSymbol *symbol = g_new0 (BinSymbol, 1);
314 symbol->name = g_strdup (name);
315 symbol->is_function = func;
316 symbol->is_global = TRUE;
317 symbol->section = acfg->cur_section;
318 /* FIXME: we align after this call... */
319 symbol->offset = symbol->section->cur_offset;
320 symbol->next = acfg->symbols;
321 acfg->symbols = symbol;
325 emit_label (MonoAotCompile *acfg, const char *name)
327 BinLabel *label = g_new0 (BinLabel, 1);
328 label->name = g_strdup (name);
329 label->section = acfg->cur_section;
330 label->offset = acfg->cur_section->cur_offset;
331 g_hash_table_insert (acfg->labels, label->name, label);
335 emit_ensure_buffer (BinSection *section, int size)
337 int new_offset = section->cur_offset + size;
338 if (new_offset >= section->data_len) {
339 int new_size = section->data_len? section->data_len * 2: 256;
341 while (new_size <= new_offset)
343 data = g_malloc0 (new_size);
344 memcpy (data, section->data, section->data_len);
345 g_free (section->data);
346 section->data = data;
347 section->data_len = new_size;
352 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
354 emit_ensure_buffer (acfg->cur_section, size);
355 memcpy (acfg->cur_section->data + acfg->cur_section->cur_offset, buf, size);
356 acfg->cur_section->cur_offset += size;
360 emit_string (MonoAotCompile *acfg, const char *value)
362 int size = strlen (value) + 1;
363 emit_bytes (acfg, (const guint8*)value, size);
367 emit_line (MonoAotCompile *acfg)
369 /* Nothing to do in binary writer */
373 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
375 emit_section_change (acfg, ".text", 1);
376 emit_global (acfg, name, FALSE);
377 emit_label (acfg, name);
378 emit_string (acfg, value);
382 emit_alignment (MonoAotCompile *acfg, int size)
384 int offset = acfg->cur_section->cur_offset;
386 offset += (size - 1);
387 offset &= ~(size - 1);
388 add = offset - acfg->cur_section->cur_offset;
390 emit_ensure_buffer (acfg->cur_section, add);
391 acfg->cur_section->cur_offset += add;
396 emit_pointer (MonoAotCompile *acfg, const char *target)
402 g_assert_not_reached ();
403 emit_alignment (acfg, sizeof (gpointer));
404 reloc = g_new0 (BinReloc, 1);
405 reloc->val1 = g_strdup (target);
406 reloc->section = acfg->cur_section;
407 reloc->section_offset = acfg->cur_section->cur_offset;
408 reloc->next = acfg->relocations;
409 acfg->relocations = reloc;
410 if (strcmp (reloc->section->name, ".data") == 0) {
412 g_print ("reloc: %s at %d\n", target, acfg->cur_section->cur_offset);
414 acfg->cur_section->cur_offset += sizeof (gpointer);
418 emit_int16 (MonoAotCompile *acfg, int value)
421 emit_ensure_buffer (acfg->cur_section, 2);
422 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
423 acfg->cur_section->cur_offset += 2;
424 /* FIXME: little endian */
426 data [1] = value >> 8;
430 emit_int32 (MonoAotCompile *acfg, int value)
433 emit_ensure_buffer (acfg->cur_section, 4);
434 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
435 acfg->cur_section->cur_offset += 4;
436 /* FIXME: little endian */
438 data [1] = value >> 8;
439 data [2] = value >> 16;
440 data [3] = value >> 24;
444 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
447 reloc = g_new0 (BinReloc, 1);
448 reloc->val1 = g_strdup (end);
449 if (strcmp (start, ".") == 0) {
450 reloc->val2_section = acfg->cur_section;
451 reloc->val2_offset = acfg->cur_section->cur_offset;
453 reloc->val2 = g_strdup (start);
455 reloc->offset = offset;
456 reloc->section = acfg->cur_section;
457 reloc->section_offset = acfg->cur_section->cur_offset;
458 reloc->next = acfg->relocations;
459 acfg->relocations = reloc;
460 acfg->cur_section->cur_offset += 4;
461 /*if (strcmp (reloc->section->name, ".data") == 0) {
463 g_print ("reloc: %s - %s + %d at %d\n", end, start, offset, acfg->cur_section->cur_offset - 4);
468 emit_zero_bytes (MonoAotCompile *acfg, int num)
470 emit_ensure_buffer (acfg->cur_section, num);
471 acfg->cur_section->cur_offset += num;
474 #ifdef USE_ELF_WRITER
509 DYN_RELCOUNT = 0x6ffffffa
512 static const char* section_names [] = {
528 static const guint8 section_type [] = {
533 static const guint8 section_link [] = {
534 0, 2, 3, 0, 2, 0, 3, 0, 0, 0, 0, 12, 0
537 static const guint8 section_esize [] = {
538 0, 4, 16, 0, 8, 0, 8, 4, 0, 0, 0, 16, 0
541 static const guint8 section_flags [] = {
542 0, 2, 2, 2, 2, 6, 3, 3, 3, 3, 0, 0, 0
545 static const guint16 section_align [] = {
546 0, 4, 4, 1, 4, 4096, 4, 4, 8, 8, 1, 4, 1
566 struct ElfSectHeader {
579 #if SIZEOF_VOID_P == 4
581 struct ElfProgHeader {
613 struct ElfProgHeader {
657 str_table_add (ElfStrTable *table, const char* value)
661 table->data = g_string_new_len ("", 1);
662 table->hash = g_hash_table_new (g_str_hash, g_str_equal);
664 idx = GPOINTER_TO_UINT (g_hash_table_lookup (table->hash, value));
667 idx = table->data->len;
668 g_string_append (table->data, value);
669 g_string_append_c (table->data, 0);
670 g_hash_table_insert (table->hash, (void*)value, GUINT_TO_POINTER (idx));
675 append_subsection (MonoAotCompile *acfg, struct ElfSectHeader *sheaders, BinSection *sect, BinSection *add)
677 int offset = sect->cur_offset;
678 /*offset += (sheaders [sect->shidx].sh_addralign - 1);
679 offset &= ~(sheaders [sect->shidx].sh_addralign - 1);*/
682 emit_ensure_buffer (sect, offset);
683 g_print ("section %s aligned to %d from %d\n", sect->name, offset, sect->cur_offset);
684 sect->cur_offset = offset;
686 emit_ensure_buffer (sect, add->cur_offset);
687 memcpy (sect->data + sect->cur_offset, add->data, add->cur_offset);
689 sect->cur_offset += add->cur_offset;
690 add->cur_offset = offset; /* it becomes the offset in the parent section */
691 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);
696 /* merge the subsections */
698 collect_sections (MonoAotCompile *acfg, struct ElfSectHeader *sheaders, BinSection **out, int num)
700 int i, j, maxs, num_sections;
705 for (sect = acfg->sections; sect; sect = sect->next) {
706 if (sect->subsection == 0) {
707 out [num_sections++] = sect;
708 g_assert (num_sections < num);
709 if (strcmp (sect->name, ".text") == 0) {
710 sect->shidx = SECT_TEXT;
711 } else if (strcmp (sect->name, ".data") == 0) {
712 sect->shidx = SECT_DATA;
713 } else if (strcmp (sect->name, ".bss") == 0) {
714 sect->shidx = SECT_BSS;
717 maxs = MAX (maxs, sect->subsection);
719 for (i = 0; i < num_sections; i++) {
720 for (j = 1; j <= maxs; ++j) {
721 for (sect = acfg->sections; sect; sect = sect->next) {
722 if (sect->subsection == j && strcmp (out [i]->name, sect->name) == 0) {
723 append_subsection (acfg, sheaders, out [i], sect);
732 elf_hash (const unsigned char *name)
734 unsigned long h = 0, g;
736 h = (h << 4) + *name++;
737 if ((g = h & 0xf0000000))
744 #define NUM_BUCKETS 17
747 build_hash (MonoAotCompile *acfg, int num_sections, ElfStrTable *dynstr)
750 int num_symbols = 1 + num_sections + 3;
753 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
754 if (!symbol->is_global)
757 str_table_add (dynstr, symbol->name);
758 /*g_print ("adding sym: %s\n", symbol->name);*/
760 str_table_add (dynstr, "__bss_start");
761 str_table_add (dynstr, "_edata");
762 str_table_add (dynstr, "_end");
764 data = g_new0 (int, num_symbols + 2 + NUM_BUCKETS);
765 data [0] = NUM_BUCKETS;
766 data [1] = num_symbols;
772 get_label_addr (MonoAotCompile *acfg, const char *name)
779 lab = g_hash_table_lookup (acfg->labels, name);
780 section = lab->section;
781 offset = lab->offset;
782 if (section->parent) {
783 value = section->parent->file_offset + section->cur_offset + offset;
785 value = section->file_offset + offset;
791 collect_syms (MonoAotCompile *acfg, int *hash, ElfStrTable *strtab, struct ElfSectHeader *sheaders, int *num_syms)
802 symbols = g_new0 (ElfSymbol, hash [1]);
804 symbols = g_new0 (ElfSymbol, *num_syms + SECT_NUM + 10); /* FIXME */
806 /* the first symbol is undef, all zeroes */
810 for (j = 1; j < SECT_NUM; ++j) {
811 symbols [i].st_info = SYM_LOCAL | SYM_SECTION;
812 symbols [i].st_shndx = j;
813 symbols [i].st_value = sheaders [j].sh_addr;
817 for (section = acfg->sections; section; section = section->next) {
820 symbols [i].st_info = SYM_LOCAL | SYM_SECTION;
821 if (strcmp (section->name, ".text") == 0) {
822 symbols [i].st_shndx = SECT_TEXT;
823 section->shidx = SECT_TEXT;
824 section->file_offset = 4096;
825 symbols [i].st_value = section->file_offset;
826 } else if (strcmp (section->name, ".data") == 0) {
827 symbols [i].st_shndx = SECT_DATA;
828 section->shidx = SECT_DATA;
829 section->file_offset = 4096 + 28; /* FIXME */
830 symbols [i].st_value = section->file_offset;
831 } else if (strcmp (section->name, ".bss") == 0) {
832 symbols [i].st_shndx = SECT_BSS;
833 section->shidx = SECT_BSS;
834 section->file_offset = 4096 + 28 + 8; /* FIXME */
835 symbols [i].st_value = section->file_offset;
840 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
843 if (!symbol->is_global)
845 symbols [i].st_info = (symbol->is_function? SYM_FUNC : SYM_OBJECT) | SYM_GLOBAL;
846 symbols [i].st_name = str_table_add (strtab, symbol->name);
847 /*g_print ("sym name %s tabled to %d\n", symbol->name, symbols [i].st_name);*/
848 section = symbol->section;
849 symbols [i].st_shndx = section->parent? section->parent->shidx: section->shidx;
850 lab = g_hash_table_lookup (acfg->labels, symbol->name);
851 offset = lab->offset;
852 if (section->parent) {
853 symbols [i].st_value = section->parent->file_offset + section->cur_offset + offset;
855 symbols [i].st_value = section->file_offset + offset;
859 /* add special symbols */
860 symbols [i].st_name = str_table_add (strtab, "__bss_start");
861 symbols [i].st_shndx = 0xfff1;
862 symbols [i].st_info = SYM_GLOBAL;
864 symbols [i].st_name = str_table_add (strtab, "_edata");
865 symbols [i].st_shndx = 0xfff1;
866 symbols [i].st_info = SYM_GLOBAL;
868 symbols [i].st_name = str_table_add (strtab, "_end");
869 symbols [i].st_shndx = 0xfff1;
870 symbols [i].st_info = SYM_GLOBAL;
876 /* add to hash table */
879 chain = hash + 2 + hash [0];
880 for (i = 0; i < hash [1]; ++i) {
882 /*g_print ("checking %d '%s' (sym %d)\n", symbols [i].st_name, strtab->data->str + symbols [i].st_name, i);*/
883 if (!symbols [i].st_name)
885 hashc = elf_hash ((guint8*)strtab->data->str + symbols [i].st_name);
886 slot = hashc % hash [0];
887 /*g_print ("hashing '%s' at slot %d (sym %d)\n", strtab->data->str + symbols [i].st_name, slot, i);*/
889 chain [i] = bucket [slot];
900 reloc_symbols (MonoAotCompile *acfg, ElfSymbol *symbols, struct ElfSectHeader *sheaders, ElfStrTable *strtab, gboolean dynamic)
908 for (section = acfg->sections; section; section = section->next) {
911 symbols [i].st_value = sheaders [section->shidx].sh_addr;
915 for (i = 1; i < SECT_NUM; ++i) {
916 symbols [i].st_value = sheaders [i].sh_addr;
919 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
922 if (dynamic && !symbol->is_global)
924 section = symbol->section;
925 lab = g_hash_table_lookup (acfg->labels, symbol->name);
926 offset = lab->offset;
927 if (section->parent) {
928 symbols [i].st_value = sheaders [section->parent->shidx].sh_addr + section->cur_offset + offset;
930 symbols [i].st_value = sheaders [section->shidx].sh_addr + offset;
935 symbols [i].st_value = sheaders [SECT_BSS].sh_addr;
938 symbols [i].st_value = sheaders [SECT_DATA].sh_addr + sheaders [SECT_DATA].sh_size;
941 symbols [i].st_value = sheaders [SECT_BSS].sh_addr + sheaders [SECT_BSS].sh_size;
946 resolve_relocations (MonoAotCompile *acfg)
950 gsize end_val, start_val;
955 rr = g_new0 (ElfReloc, acfg->num_relocs);
958 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
959 end_val = get_label_addr (acfg, reloc->val1);
961 start_val = get_label_addr (acfg, reloc->val2);
962 } else if (reloc->val2_section) {
963 start_val = reloc->val2_offset;
964 if (reloc->val2_section->parent)
965 start_val += reloc->val2_section->parent->file_offset + reloc->val2_section->cur_offset;
967 start_val += reloc->val2_section->file_offset;
971 end_val = end_val - start_val + reloc->offset;
972 if (reloc->section->parent) {
973 data = reloc->section->parent->data;
974 data += reloc->section->cur_offset;
975 data += reloc->section_offset;
976 vaddr = reloc->section->parent->file_offset;
977 vaddr += reloc->section->cur_offset;
978 vaddr += reloc->section_offset;
980 data = reloc->section->data;
981 data += reloc->section_offset;
982 vaddr = reloc->section->file_offset;
983 vaddr += reloc->section_offset;
985 /* FIXME: little endian */
987 data [1] = end_val >> 8;
988 data [2] = end_val >> 16;
989 data [3] = end_val >> 24;
990 if (start_val == 0) {
992 rr [i].value = 8; /* FIXME: 386_RELATIVE */
994 g_assert (i <= acfg->num_relocs);
1001 emit_writeout (MonoAotCompile *acfg)
1003 char *outfile_name, *tmp_outfile_name;
1005 struct ElfHeader header;
1006 struct ElfProgHeader progh [3];
1007 struct ElfSectHeader secth [SECT_NUM];
1009 ElfStrTable str_table = {NULL, NULL};
1010 ElfStrTable sh_str_table = {NULL, NULL};
1011 ElfStrTable dyn_str_table = {NULL, NULL};
1012 BinSection* sections [6];
1013 BinSection *text_section = NULL, *data_section = NULL, *bss_section = NULL;
1016 ElfDynamic dynamic [14];
1018 int i, num_sections, file_offset, virt_offset, size, num_symtab;
1021 g_assert (!acfg->aot_opts.asm_only);
1023 if (acfg->aot_opts.outfile)
1024 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1026 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1028 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1030 unlink (tmp_outfile_name);
1031 file = fopen (tmp_outfile_name, "w");
1034 /* Section headers */
1035 memset (§h, 0, sizeof (secth));
1036 memset (&dynamic, 0, sizeof (dynamic));
1037 memset (&header, 0, sizeof (header));
1039 for (i = 1; i < SECT_NUM; ++i) {
1040 secth [i].sh_name = str_table_add (&sh_str_table, section_names [i]);
1041 secth [i].sh_type = section_type [i];
1042 secth [i].sh_link = section_link [i];
1043 secth [i].sh_addralign = section_align [i];
1044 secth [i].sh_flags = section_flags [i];
1045 secth [i].sh_entsize = section_esize [i];
1047 secth [SECT_DYNSYM].sh_info = 4;
1048 secth [SECT_SYMTAB].sh_info = 20;
1050 num_sections = collect_sections (acfg, secth, sections, 6);
1051 hash = build_hash (acfg, num_sections, &dyn_str_table);
1052 num_symtab = hash [1]; /* FIXME */
1053 g_print ("num_sections: %d\n", num_sections);
1054 g_print ("dynsym: %d, dynstr size: %d\n", hash [1], dyn_str_table.data->len);
1055 for (i = 0; i < num_sections; ++i) {
1056 g_print ("section %s, size: %d, %x\n", sections [i]->name, sections [i]->cur_offset, sections [i]->cur_offset);
1059 /* at this point we know where in the file the first segment sections go */
1060 dynsym = collect_syms (acfg, hash, &dyn_str_table, NULL, NULL);
1061 num_local_syms = hash [1];
1062 symtab = collect_syms (acfg, NULL, &str_table, secth, &num_local_syms);
1064 for (i = 0; i < num_sections; ++i) {
1065 if (sections [i]->shidx == SECT_TEXT) {
1066 text_section = sections [i];
1067 } else if (sections [i]->shidx == SECT_DATA) {
1068 data_section = sections [i];
1069 } else if (sections [i]->shidx == SECT_BSS) {
1070 bss_section = sections [i];
1074 file_offset = virt_offset = sizeof (header) + sizeof (progh);
1075 secth [SECT_HASH].sh_addr = secth [SECT_HASH].sh_offset = file_offset;
1076 size = sizeof (int) * (2 + hash [0] + hash [1]);
1077 virt_offset = (file_offset += size);
1078 secth [SECT_HASH].sh_size = size;
1079 secth [SECT_DYNSYM].sh_addr = secth [SECT_DYNSYM].sh_offset = file_offset;
1080 size = sizeof (ElfSymbol) * hash [1];
1081 virt_offset = (file_offset += size);
1082 secth [SECT_DYNSYM].sh_size = size;
1083 secth [SECT_DYNSTR].sh_addr = secth [SECT_DYNSTR].sh_offset = file_offset;
1084 size = dyn_str_table.data->len;
1085 virt_offset = (file_offset += size);
1086 secth [SECT_DYNSTR].sh_size = size;
1088 file_offset &= ~(4-1);
1089 secth [SECT_REL_DYN].sh_addr = secth [SECT_REL_DYN].sh_offset = file_offset;
1090 size = sizeof (ElfReloc) * acfg->num_relocs;
1091 secth [SECT_REL_DYN].sh_size = size;
1092 virt_offset = (file_offset += size);
1093 secth [SECT_REL_DYN].sh_size = size;
1094 file_offset += 4096-1;
1095 file_offset &= ~(4096-1);
1096 virt_offset = file_offset;
1097 secth [SECT_TEXT].sh_addr = secth [SECT_TEXT].sh_offset = file_offset;
1098 size = text_section->cur_offset;
1099 secth [SECT_TEXT].sh_size = size;
1100 file_offset += size;
1102 file_offset &= ~(4-1);
1103 virt_offset = file_offset;
1104 /* .dynamic, .got.plt, .data, .bss here */
1105 secth [SECT_DYNAMIC].sh_addr = virt_offset;
1106 secth [SECT_DYNAMIC].sh_offset = file_offset;
1107 size = sizeof (dynamic);
1108 secth [SECT_DYNAMIC].sh_size = size;
1111 file_offset += size;
1112 virt_offset += size;
1113 secth [SECT_GOT_PLT].sh_addr = virt_offset;
1114 secth [SECT_GOT_PLT].sh_offset = file_offset;
1116 secth [SECT_GOT_PLT].sh_size = size;
1119 file_offset += size;
1120 virt_offset += size;
1121 secth [SECT_DATA].sh_addr = virt_offset;
1122 secth [SECT_DATA].sh_offset = file_offset;
1123 size = data_section->cur_offset;
1124 secth [SECT_DATA].sh_size = size;
1127 file_offset += size;
1128 virt_offset += size;
1129 secth [SECT_BSS].sh_addr = virt_offset;
1130 secth [SECT_BSS].sh_offset = file_offset;
1131 size = bss_section->cur_offset;
1132 secth [SECT_BSS].sh_size = size;
1134 /* virtual doesn't matter anymore */
1135 secth [SECT_SHSTRTAB].sh_offset = file_offset;
1136 size = sh_str_table.data->len;
1137 secth [SECT_SHSTRTAB].sh_size = size;
1140 file_offset += size;
1141 secth [SECT_SYMTAB].sh_offset = file_offset;
1142 size = sizeof (ElfSymbol) * num_local_syms;
1143 secth [SECT_SYMTAB].sh_size = size;
1144 file_offset += size;
1145 secth [SECT_STRTAB].sh_offset = file_offset;
1146 size = str_table.data->len;
1147 secth [SECT_STRTAB].sh_size = size;
1148 file_offset += size;
1150 file_offset &= ~(4-1);
1152 text_section->file_offset = secth [SECT_TEXT].sh_offset;
1153 data_section->file_offset = secth [SECT_DATA].sh_offset;
1154 bss_section->file_offset = secth [SECT_BSS].sh_offset;
1156 header.e_ident [0] = 0x7f; header.e_ident [1] = 'E';
1157 header.e_ident [2] = 'L'; header.e_ident [3] = 'F';
1158 header.e_ident [4] = SIZEOF_VOID_P == 4? 1: 2;
1159 header.e_ident [5] = 1; /* FIXME: little endian, bigendian is 2 */
1160 header.e_ident [6] = 1; /* version */
1161 header.e_ident [7] = 0; /* FIXME: */
1162 header.e_ident [8] = 0; /* FIXME: */
1163 for (i = 9; i < 16; ++i)
1164 header.e_ident [i] = 0;
1166 header.e_type = 3; /* shared library */
1167 header.e_machine = 3; /* FIXME: 386 */
1168 header.e_version = 1; /* FIXME: */
1170 header.e_phoff = sizeof (header);
1171 header.e_ehsize = sizeof (header);
1172 header.e_phentsize = sizeof (struct ElfProgHeader);
1174 header.e_entry = secth [SECT_TEXT].sh_addr;
1175 header.e_shstrndx = 10;
1176 header.e_shentsize = sizeof (struct ElfSectHeader);
1177 header.e_shnum = SECT_NUM;
1178 header.e_shoff = file_offset;
1182 dynamic [i].d_tag = DYN_HASH;
1183 dynamic [i].d_val = secth [SECT_HASH].sh_offset;
1185 dynamic [i].d_tag = DYN_STRTAB;
1186 dynamic [i].d_val = secth [SECT_DYNSTR].sh_offset;
1188 dynamic [i].d_tag = DYN_SYMTAB;
1189 dynamic [i].d_val = secth [SECT_DYNSYM].sh_offset;
1191 dynamic [i].d_tag = DYN_STRSZ;
1192 dynamic [i].d_val = dyn_str_table.data->len;
1194 dynamic [i].d_tag = DYN_SYMENT;
1195 dynamic [i].d_val = sizeof (ElfSymbol);
1197 dynamic [i].d_tag = DYN_REL;
1198 dynamic [i].d_val = secth [SECT_REL_DYN].sh_offset;
1200 dynamic [i].d_tag = DYN_RELSZ;
1201 dynamic [i].d_val = secth [SECT_REL_DYN].sh_size;
1203 dynamic [i].d_tag = DYN_RELENT;
1204 dynamic [i].d_val = sizeof (ElfReloc);
1206 dynamic [i].d_tag = DYN_RELCOUNT;
1207 dynamic [i].d_val = acfg->num_relocs;
1210 /* Program header */
1211 memset (&progh, 0, sizeof (progh));
1212 progh [0].p_type = 1; /* LOAD */
1213 progh [0].p_filesz = progh [0].p_memsz = secth [SECT_DYNAMIC].sh_offset;
1214 progh [0].p_align = 4096;
1215 progh [0].p_flags = 5;
1217 progh [1].p_type = 1;
1218 progh [1].p_offset = secth [SECT_DYNAMIC].sh_offset;
1219 progh [1].p_vaddr = progh [1].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1220 progh [1].p_filesz = secth [SECT_BSS].sh_offset - secth [SECT_DYNAMIC].sh_offset;
1221 progh [1].p_memsz = secth [SECT_BSS].sh_addr + secth [SECT_BSS].sh_size - secth [SECT_DYNAMIC].sh_addr;
1222 progh [1].p_align = 4096;
1223 progh [1].p_flags = 6;
1225 progh [2].p_type = 2; /* DYNAMIC */
1226 progh [2].p_offset = secth [SECT_DYNAMIC].sh_offset;
1227 progh [2].p_vaddr = progh [2].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1228 progh [2].p_filesz = progh [2].p_memsz = secth [SECT_DYNAMIC].sh_size;
1229 progh [2].p_align = 4;
1230 progh [2].p_flags = 6;
1232 reloc_symbols (acfg, dynsym, secth, &dyn_str_table, TRUE);
1233 reloc_symbols (acfg, symtab, secth, &str_table, FALSE);
1234 relocs = resolve_relocations (acfg);
1236 fwrite (&header, sizeof (header), 1, file);
1237 fwrite (&progh, sizeof (progh), 1, file);
1238 fwrite (hash, sizeof (int) * (hash [0] + hash [1] + 2), 1, file);
1239 fwrite (dynsym, sizeof (ElfSymbol) * hash [1], 1, file);
1240 fwrite (dyn_str_table.data->str, dyn_str_table.data->len, 1, file);
1242 fseek (file, secth [SECT_REL_DYN].sh_offset, SEEK_SET);
1243 fwrite (relocs, sizeof (ElfReloc), acfg->num_relocs, file);
1245 fseek (file, secth [SECT_TEXT].sh_offset, SEEK_SET);
1246 /* write .text, .data, .bss sections */
1247 fwrite (text_section->data, text_section->cur_offset, 1, file);
1250 fwrite (dynamic, sizeof (dynamic), 1, file);
1252 size = secth [SECT_DYNAMIC].sh_addr;
1253 fwrite (&size, sizeof (size), 1, file);
1254 fseek (file, secth [SECT_DATA].sh_offset, SEEK_SET);
1255 fwrite (data_section->data, data_section->cur_offset, 1, file);
1257 fseek (file, secth [SECT_SHSTRTAB].sh_offset, SEEK_SET);
1258 fwrite (sh_str_table.data->str, sh_str_table.data->len, 1, file);
1259 fseek (file, secth [SECT_SYMTAB].sh_offset, SEEK_SET);
1260 fwrite (symtab, sizeof (ElfSymbol) * num_local_syms, 1, file);
1261 fseek (file, secth [SECT_STRTAB].sh_offset, SEEK_SET);
1262 fwrite (str_table.data->str, str_table.data->len, 1, file);
1263 /*g_print ("file_offset %d vs %d\n", file_offset, ftell (file));*/
1264 /*g_assert (file_offset >= ftell (file));*/
1265 fseek (file, file_offset, SEEK_SET);
1266 fwrite (§h, sizeof (secth), 1, file);
1268 rename (tmp_outfile_name, outfile_name);
1270 g_free (tmp_outfile_name);
1271 g_free (outfile_name);
1276 #endif /* USE_ELF_WRITER */
1281 emit_start (MonoAotCompile *acfg)
1283 if (acfg->aot_opts.asm_only) {
1284 if (acfg->aot_opts.outfile)
1285 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1287 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
1288 acfg->fp = fopen (acfg->tmpfname, "w+");
1290 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
1291 acfg->fp = fdopen (i, "w+");
1293 g_assert (acfg->fp);
1297 emit_unset_mode (MonoAotCompile *acfg)
1299 if (acfg->mode == EMIT_NONE)
1301 fprintf (acfg->fp, "\n");
1302 acfg->mode = EMIT_NONE;
1306 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
1308 emit_unset_mode (acfg);
1309 #if defined(PLATFORM_WIN32)
1310 fprintf (acfg->fp, ".section %s\n", section_name);
1311 #elif defined(__MACH__)
1312 if (strcmp(section_name, ".bss") == 0)
1313 fprintf (acfg->fp, "%s\n", ".data");
1315 fprintf (acfg->fp, "%s\n", section_name);
1316 #elif defined(sparc) || defined(__arm__)
1317 /* For solaris as, GNU as should accept the same */
1318 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1320 fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1325 emit_symbol_type (MonoAotCompile *acfg, const char *name, gboolean func)
1334 emit_unset_mode (acfg);
1335 #if defined(__MACH__)
1337 #elif defined(sparc) || defined(__arm__)
1338 fprintf (acfg->fp, "\t.type %s,#%s\n", name, stype);
1339 #elif defined(PLATFORM_WIN32)
1341 #elif defined(__x86_64__) || defined(__i386__)
1342 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1344 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1349 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
1351 emit_unset_mode (acfg);
1352 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1353 // mach-o always uses a '_' prefix.
1354 fprintf (acfg->fp, "\t.globl _%s\n", name);
1356 fprintf (acfg->fp, "\t.globl %s\n", name);
1359 emit_symbol_type (acfg, name, func);
1363 emit_label (MonoAotCompile *acfg, const char *name)
1365 emit_unset_mode (acfg);
1366 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1367 // mach-o always uses a '_' prefix.
1368 fprintf (acfg->fp, "_%s:\n", name);
1370 fprintf (acfg->fp, "%s:\n", name);
1373 #if defined(PLATFORM_WIN32)
1374 /* Emit a normal label too */
1375 fprintf (acfg->fp, "%s:\n", name);
1380 emit_string (MonoAotCompile *acfg, const char *value)
1382 emit_unset_mode (acfg);
1383 fprintf (acfg->fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
1387 emit_line (MonoAotCompile *acfg)
1389 emit_unset_mode (acfg);
1390 fprintf (acfg->fp, "\n");
1394 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
1396 emit_unset_mode (acfg);
1397 emit_section_change (acfg, ".text", 1);
1398 emit_global (acfg, name, FALSE);
1399 emit_label (acfg, name);
1400 emit_string (acfg, value);
1404 emit_alignment (MonoAotCompile *acfg, int size)
1406 emit_unset_mode (acfg);
1407 #if defined(__arm__)
1408 fprintf (acfg->fp, "\t.align %d\n", ilog2 (size));
1409 #elif defined(__ppc__) && defined(__MACH__)
1410 // the mach-o assembler specifies alignments as powers of 2.
1411 fprintf (acfg->fp, "\t.align %d\t; ilog2\n", ilog2(size));
1412 #elif defined(__powerpc__)
1413 /* ignore on linux/ppc */
1415 fprintf (acfg->fp, "\t.align %d\n", size);
1420 emit_pointer (MonoAotCompile *acfg, const char *target)
1422 emit_unset_mode (acfg);
1423 emit_alignment (acfg, sizeof (gpointer));
1424 #if defined(__x86_64__)
1425 fprintf (acfg->fp, "\t.quad %s\n", target ? target : "0");
1426 #elif defined(sparc) && SIZEOF_VOID_P == 8
1427 fprintf (acfg->fp, "\t.xword %s\n", target ? target : "0");
1429 fprintf (acfg->fp, "\t.long %s\n", target ? target : "0");
1434 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
1437 if (acfg->mode != EMIT_BYTE) {
1438 acfg->mode = EMIT_BYTE;
1439 acfg->col_count = 0;
1441 for (i = 0; i < size; ++i, ++acfg->col_count) {
1442 if ((acfg->col_count % 32) == 0)
1443 fprintf (acfg->fp, "\n\t.byte ");
1445 fprintf (acfg->fp, ",");
1446 fprintf (acfg->fp, "0x%x", buf [i]);
1451 emit_int16 (MonoAotCompile *acfg, int value)
1453 if (acfg->mode != EMIT_WORD) {
1454 acfg->mode = EMIT_WORD;
1455 acfg->col_count = 0;
1457 if ((acfg->col_count++ % 8) == 0)
1458 #if defined(__MACH__)
1459 fprintf (acfg->fp, "\n\t.short ");
1460 #elif defined(__arm__)
1461 /* FIXME: Use .hword on other archs as well */
1462 fprintf (acfg->fp, "\n\t.hword ");
1464 fprintf (acfg->fp, "\n\t.word ");
1467 fprintf (acfg->fp, ", ");
1468 fprintf (acfg->fp, "%d", value);
1472 emit_int32 (MonoAotCompile *acfg, int value)
1474 if (acfg->mode != EMIT_LONG) {
1475 acfg->mode = EMIT_LONG;
1476 acfg->col_count = 0;
1478 if ((acfg->col_count++ % 8) == 0)
1479 fprintf (acfg->fp, "\n\t.long ");
1481 fprintf (acfg->fp, ",");
1482 fprintf (acfg->fp, "%d", value);
1486 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
1488 if (acfg->mode != EMIT_LONG) {
1489 acfg->mode = EMIT_LONG;
1490 acfg->col_count = 0;
1492 if ((acfg->col_count++ % 8) == 0)
1493 fprintf (acfg->fp, "\n\t.long ");
1495 fprintf (acfg->fp, ",");
1497 fprintf (acfg->fp, "%s - %s + %d", end, start, offset);
1498 else if (offset < 0)
1499 fprintf (acfg->fp, "%s - %s %d", end, start, offset);
1501 fprintf (acfg->fp, "%s - %s", end, start);
1505 emit_zero_bytes (MonoAotCompile *acfg, int num)
1507 emit_unset_mode (acfg);
1508 #if defined(__MACH__)
1509 fprintf (acfg->fp, "\t.space %d\n", num);
1511 fprintf (acfg->fp, "\t.skip %d\n", num);
1516 emit_writeout (MonoAotCompile *acfg)
1518 char *command, *objfile;
1519 char *outfile_name, *tmp_outfile_name;
1523 #if defined(__x86_64__)
1524 #define AS_OPTIONS "--64"
1525 #elif defined(sparc) && SIZEOF_VOID_P == 8
1526 #define AS_OPTIONS "-xarch=v9"
1528 #define AS_OPTIONS ""
1531 if (acfg->aot_opts.asm_only) {
1532 printf ("Output file: '%s'.\n", acfg->tmpfname);
1533 if (acfg->aot_opts.static_link)
1534 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1538 if (acfg->aot_opts.static_link) {
1539 if (acfg->aot_opts.outfile)
1540 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1542 objfile = g_strdup_printf ("%s.o", acfg->image->name);
1544 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
1546 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
1547 printf ("Executing the native assembler: %s\n", command);
1548 if (system (command) != 0) {
1556 if (acfg->aot_opts.static_link) {
1557 printf ("Output file: '%s'.\n", objfile);
1558 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1563 if (acfg->aot_opts.outfile)
1564 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1566 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1568 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1571 command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
1572 #elif defined(__ppc__) && defined(__MACH__)
1573 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
1574 #elif defined(PLATFORM_WIN32)
1575 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
1577 if (acfg->aot_opts.no_dlsym) {
1579 * Need to link using gcc so our ctor function gets called.
1581 command = g_strdup_printf ("gcc -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1583 command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1586 printf ("Executing the native linker: %s\n", command);
1587 if (system (command) != 0) {
1588 g_free (tmp_outfile_name);
1589 g_free (outfile_name);
1597 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
1598 printf ("Stripping the binary: %s\n", com);
1602 rename (tmp_outfile_name, outfile_name);
1604 g_free (tmp_outfile_name);
1605 g_free (outfile_name);
1608 if (acfg->aot_opts.save_temps)
1609 printf ("Retained input file.\n");
1611 unlink (acfg->tmpfname);
1616 #endif /* ASM_WRITER */
1619 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
1621 if (acfg->aot_opts.no_dlsym) {
1622 g_ptr_array_add (acfg->globals, g_strdup (name));
1624 emit_global_inner (acfg, name, func);
1629 emit_byte (MonoAotCompile *acfg, guint8 val)
1631 emit_bytes (acfg, &val, 1);
1635 mono_get_field_token (MonoClassField *field)
1637 MonoClass *klass = field->parent;
1640 for (i = 0; i < klass->field.count; ++i) {
1641 if (field == &klass->fields [i])
1642 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1645 g_assert_not_reached ();
1650 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1654 //printf ("ENCODE: %d 0x%x.\n", value, value);
1657 * Same encoding as the one used in the metadata, extended to handle values
1658 * greater than 0x1fffffff.
1660 if ((value >= 0) && (value <= 127))
1662 else if ((value >= 0) && (value <= 16383)) {
1663 p [0] = 0x80 | (value >> 8);
1664 p [1] = value & 0xff;
1666 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1667 p [0] = (value >> 24) | 0xc0;
1668 p [1] = (value >> 16) & 0xff;
1669 p [2] = (value >> 8) & 0xff;
1670 p [3] = value & 0xff;
1675 p [1] = (value >> 24) & 0xff;
1676 p [2] = (value >> 16) & 0xff;
1677 p [3] = (value >> 8) & 0xff;
1678 p [4] = value & 0xff;
1686 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1690 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1694 index = g_hash_table_size (cfg->image_hash);
1695 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1696 g_ptr_array_add (cfg->image_table, image);
1702 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1705 MonoClass *k = NULL;
1707 /* FIXME: Search referenced images as well */
1708 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1709 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1714 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1715 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1721 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1726 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1727 * standard metadata encoding.
1730 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1734 if (klass->generic_class) {
1736 g_assert (klass->type_token);
1738 /* Find a typespec for a class if possible */
1739 token = find_typespec_for_class (acfg, klass);
1741 encode_value (token, p, &p);
1742 encode_value (get_image_index (acfg, acfg->image), p, &p);
1744 MonoClass *gclass = klass->generic_class->container_class;
1745 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1748 /* Encode it ourselves */
1750 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1751 encode_value (MONO_TYPE_GENERICINST, p, &p);
1752 encode_klass_ref (acfg, gclass, p, &p);
1753 encode_value (inst->type_argc, p, &p);
1754 for (i = 0; i < inst->type_argc; ++i)
1755 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1757 } else if (klass->type_token) {
1758 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1759 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1760 encode_value (get_image_index (acfg, klass->image), p, &p);
1761 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1762 MonoGenericParam *param = klass->byval_arg.data.generic_param;
1765 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1766 encode_value (klass->byval_arg.type, p, &p);
1768 encode_value (param->num, p, &p);
1770 g_assert (param->owner);
1771 encode_value (param->owner->is_method, p, &p);
1772 if (param->owner->is_method)
1773 encode_method_ref (acfg, param->owner->owner.method, p, &p);
1775 encode_klass_ref (acfg, param->owner->owner.klass, p, &p);
1778 g_assert (klass->rank > 0);
1779 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1780 encode_value (get_image_index (acfg, klass->image), p, &p);
1781 encode_value (klass->rank, p, &p);
1782 encode_klass_ref (acfg, klass->element_class, p, &p);
1788 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1790 guint32 token = mono_get_field_token (field);
1793 encode_klass_ref (cfg, field->parent, p, &p);
1794 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1795 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1799 #define MAX_IMAGE_INDEX 250
1802 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1804 guint32 image_index = get_image_index (acfg, method->klass->image);
1805 guint32 token = method->token;
1806 MonoJumpInfoToken *ji;
1809 g_assert (image_index < MAX_IMAGE_INDEX);
1811 /* Mark methods which can't use aot trampolines because they need the further
1812 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1814 if (method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
1815 encode_value ((252 << 24), p, &p);
1817 if (method->wrapper_type) {
1819 encode_value ((253 << 24), p, &p);
1821 encode_value (method->wrapper_type, p, &p);
1823 switch (method->wrapper_type) {
1824 case MONO_WRAPPER_REMOTING_INVOKE:
1825 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1826 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1829 m = mono_marshal_method_from_wrapper (method);
1831 encode_method_ref (acfg, m, p, &p);
1834 case MONO_WRAPPER_PROXY_ISINST:
1835 case MONO_WRAPPER_LDFLD:
1836 case MONO_WRAPPER_LDFLDA:
1837 case MONO_WRAPPER_STFLD:
1838 case MONO_WRAPPER_ISINST: {
1839 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1840 encode_klass_ref (acfg, proxy_class, p, &p);
1843 case MONO_WRAPPER_LDFLD_REMOTE:
1844 case MONO_WRAPPER_STFLD_REMOTE:
1846 case MONO_WRAPPER_ALLOC: {
1847 int alloc_type = mono_gc_get_managed_allocator_type (method);
1848 g_assert (alloc_type != -1);
1849 encode_value (alloc_type, p, &p);
1852 case MONO_WRAPPER_STELEMREF:
1854 case MONO_WRAPPER_STATIC_RGCTX_INVOKE: {
1857 m = mono_marshal_method_from_wrapper (method);
1859 encode_method_ref (acfg, m, p, &p);
1863 g_assert_not_reached ();
1865 } else if (mono_method_signature (method)->is_inflated) {
1867 * This is a generic method, find the original token which referenced it and
1869 * Obtain the token from information recorded by the JIT.
1871 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1873 image_index = get_image_index (acfg, ji->image);
1874 g_assert (image_index < MAX_IMAGE_INDEX);
1878 encode_value ((255 << 24), p, &p);
1879 encode_value (image_index, p, &p);
1880 encode_value (token, p, &p);
1882 MonoMethod *declaring;
1883 MonoGenericContext *context = mono_method_get_context (method);
1884 MonoGenericInst *inst;
1887 g_assert (method->is_inflated);
1888 declaring = ((MonoMethodInflated*)method)->declaring;
1891 * This might be a non-generic method of a generic instance, which
1892 * doesn't have a token since the reference is generated by the JIT
1893 * like Nullable:Box/Unbox, or by generic sharing.
1897 encode_value ((254 << 24), p, &p);
1898 /* Encode the klass */
1899 encode_klass_ref (acfg, method->klass, p, &p);
1900 /* Encode the method */
1901 image_index = get_image_index (acfg, method->klass->image);
1902 g_assert (image_index < MAX_IMAGE_INDEX);
1903 g_assert (declaring->token);
1904 token = declaring->token;
1905 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1906 encode_value (image_index, p, &p);
1907 encode_value (token, p, &p);
1909 /* Encode the context */
1910 inst = context->class_inst;
1911 encode_value (inst ? 1 : 0, p, &p);
1913 encode_value (inst->type_argc, p, &p);
1914 for (i = 0; i < inst->type_argc; ++i)
1915 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1917 inst = context->method_inst;
1918 encode_value (inst ? 1 : 0, p, &p);
1920 encode_value (inst->type_argc, p, &p);
1921 for (i = 0; i < inst->type_argc; ++i)
1922 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1925 } else if (token == 0) {
1926 /* This might be a method of a constructed type like int[,].Set */
1927 /* Obtain the token from information recorded by the JIT */
1928 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1930 image_index = get_image_index (acfg, ji->image);
1931 g_assert (image_index < MAX_IMAGE_INDEX);
1935 encode_value ((255 << 24), p, &p);
1936 encode_value (image_index, p, &p);
1937 encode_value (token, p, &p);
1939 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1940 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1946 compare_patches (gconstpointer a, gconstpointer b)
1950 i = (*(MonoJumpInfo**)a)->ip.i;
1951 j = (*(MonoJumpInfo**)b)->ip.i;
1965 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1968 static inline gboolean
1969 is_plt_patch (MonoJumpInfo *patch_info)
1971 switch (patch_info->type) {
1972 case MONO_PATCH_INFO_METHOD:
1973 case MONO_PATCH_INFO_INTERNAL_METHOD:
1974 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1975 case MONO_PATCH_INFO_CLASS_INIT:
1976 case MONO_PATCH_INFO_RGCTX_FETCH:
1977 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1985 * is_shared_got_patch:
1987 * Return whenever PATCH_INFO refers to a patch which needs a shared GOT
1989 * Keep it in sync with the version in aot-runtime.c.
1991 static inline gboolean
1992 is_shared_got_patch (MonoJumpInfo *patch_info)
1994 switch (patch_info->type) {
1995 case MONO_PATCH_INFO_VTABLE:
1996 case MONO_PATCH_INFO_CLASS:
1997 case MONO_PATCH_INFO_IID:
1998 case MONO_PATCH_INFO_ADJUSTED_IID:
1999 case MONO_PATCH_INFO_FIELD:
2000 case MONO_PATCH_INFO_SFLDA:
2001 case MONO_PATCH_INFO_DECLSEC:
2002 case MONO_PATCH_INFO_LDTOKEN:
2003 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2004 case MONO_PATCH_INFO_RVA:
2005 case MONO_PATCH_INFO_METHODCONST:
2013 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2017 if (is_plt_patch (patch_info)) {
2018 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
2023 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2025 res = acfg->plt_offset;
2026 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
2027 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
2028 acfg->plt_offset ++;
2038 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2039 * JI could be found if it exists, otherwise allocates a new one.
2042 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2046 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
2048 return got_offset - 1;
2050 got_offset = acfg->got_offset;
2051 acfg->got_offset ++;
2053 acfg->stats.got_slots ++;
2054 acfg->stats.got_slot_types [ji->type] ++;
2060 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2065 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
2066 got_offset = get_got_offset (acfg, ji);
2067 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
2068 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
2069 g_ptr_array_add (acfg->shared_patches, copy);
2072 return get_got_offset (acfg, ji);
2075 /* Add a method to the list of methods which need to be emitted */
2077 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
2079 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2080 g_ptr_array_add (acfg->methods, method);
2081 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2086 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2088 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2096 add_method (MonoAotCompile *acfg, MonoMethod *method)
2100 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2104 index = acfg->method_index;
2105 add_method_with_index (acfg, method, index);
2107 /* FIXME: Fix quadratic behavior */
2108 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2110 acfg->method_index ++;
2116 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2118 MonoAotCompile *acfg = user_data;
2119 MonoJitICallInfo *callinfo = value;
2120 MonoMethod *wrapper;
2126 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2127 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2130 add_method (acfg, wrapper);
2134 get_runtime_invoke_sig (MonoMethodSignature *sig)
2136 MonoMethodBuilder *mb;
2139 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2140 m = mono_mb_create_method (mb, sig, 16);
2141 return mono_marshal_get_runtime_invoke (m);
2145 add_wrappers (MonoAotCompile *acfg)
2147 MonoMethod *method, *m;
2148 int i, j, nallocators;
2149 MonoMethodSignature *sig, *csig;
2153 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2154 * so there is only one wrapper of a given type, or inlining their contents into their
2159 * FIXME: This depends on the fact that different wrappers have different
2163 /* FIXME: Collect these automatically */
2165 /* Runtime invoke wrappers */
2167 /* void runtime-invoke () [.cctor] */
2168 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2169 csig->ret = &mono_defaults.void_class->byval_arg;
2170 add_method (acfg, get_runtime_invoke_sig (csig));
2172 /* void runtime-invoke () [Finalize] */
2173 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2175 csig->ret = &mono_defaults.void_class->byval_arg;
2176 add_method (acfg, get_runtime_invoke_sig (csig));
2178 /* void runtime-invoke (string) [exception ctor] */
2179 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2181 csig->ret = &mono_defaults.void_class->byval_arg;
2182 csig->params [0] = &mono_defaults.string_class->byval_arg;
2183 add_method (acfg, get_runtime_invoke_sig (csig));
2185 /* void runtime-invoke (string, string) [exception ctor] */
2186 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2188 csig->ret = &mono_defaults.void_class->byval_arg;
2189 csig->params [0] = &mono_defaults.string_class->byval_arg;
2190 csig->params [1] = &mono_defaults.string_class->byval_arg;
2191 add_method (acfg, get_runtime_invoke_sig (csig));
2193 /* string runtime-invoke () [Exception.ToString ()] */
2194 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2196 csig->ret = &mono_defaults.string_class->byval_arg;
2197 add_method (acfg, get_runtime_invoke_sig (csig));
2199 /* void runtime-invoke (string, Exception) [exception ctor] */
2200 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2202 csig->ret = &mono_defaults.void_class->byval_arg;
2203 csig->params [0] = &mono_defaults.string_class->byval_arg;
2204 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2205 add_method (acfg, get_runtime_invoke_sig (csig));
2207 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2208 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2210 csig->ret = &(mono_class_from_name (
2211 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2212 csig->params [0] = &mono_defaults.string_class->byval_arg;
2213 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2214 add_method (acfg, get_runtime_invoke_sig (csig));
2216 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2218 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2219 gboolean skip = FALSE;
2221 method = mono_get_method (acfg->image, token, NULL);
2223 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2224 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2225 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2228 if (method->is_generic || method->klass->generic_container)
2231 /* Skip methods which can not be handled by get_runtime_invoke () */
2232 sig = mono_method_signature (method);
2233 if ((sig->ret->type == MONO_TYPE_PTR) ||
2234 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2237 for (j = 0; j < sig->param_count; j++) {
2238 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2243 add_method (acfg, mono_marshal_get_runtime_invoke (method));
2246 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2247 /* JIT icall wrappers */
2248 /* FIXME: locking */
2249 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2251 /* Managed Allocators */
2252 nallocators = mono_gc_get_managed_allocator_types ();
2253 for (i = 0; i < nallocators; ++i) {
2254 m = mono_gc_get_managed_allocator_by_type (i);
2256 add_method (acfg, m);
2260 add_method (acfg, mono_marshal_get_stelemref ());
2263 /* remoting-invoke wrappers */
2264 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2265 MonoMethodSignature *sig;
2267 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2268 method = mono_get_method (acfg->image, token, NULL);
2270 sig = mono_method_signature (method);
2272 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
2273 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2274 m = mono_marshal_get_remoting_invoke_with_check (method);
2276 add_method (acfg, m);
2280 /* delegate-invoke wrappers */
2281 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2284 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2285 klass = mono_class_get (acfg->image, token);
2287 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class) {
2288 method = mono_get_delegate_invoke (klass);
2290 m = mono_marshal_get_delegate_invoke (method, NULL);
2292 add_method (acfg, m);
2297 /* static rgctx wrappers */
2298 /* FIXME: Each wrapper belongs to a given instantiation of a generic method */
2299 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2300 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2301 method = mono_get_method (acfg->image, token, NULL);
2303 if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
2304 (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
2305 mono_class_generic_sharing_enabled (method->klass) &&
2306 mono_method_is_generic_sharable_impl (method, FALSE)) {
2307 m = mono_marshal_get_static_rgctx_invoke (method);
2308 add_method (acfg, m);
2315 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2317 int i, pindex, start_index, method_index;
2319 MonoJumpInfo *patch_info;
2320 MonoMethodHeader *header;
2325 header = mono_method_get_header (method);
2327 method_index = get_method_index (acfg, method);
2330 /* Collect and sort relocations */
2331 patches = g_ptr_array_new ();
2332 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2333 g_ptr_array_add (patches, patch_info);
2334 g_ptr_array_sort (patches, compare_patches);
2337 for (i = 0; i < code_len; i++) {
2339 for (pindex = start_index; pindex < patches->len; ++pindex) {
2340 patch_info = g_ptr_array_index (patches, pindex);
2341 if (patch_info->ip.i >= i)
2345 #ifdef MONO_ARCH_AOT_SUPPORTED
2347 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2348 start_index = pindex;
2350 switch (patch_info->type) {
2351 case MONO_PATCH_INFO_NONE:
2353 case MONO_PATCH_INFO_GOT_OFFSET: {
2354 guint32 offset = mono_arch_get_patch_offset (code + i);
2355 emit_bytes (acfg, code + i, offset);
2356 emit_symbol_diff (acfg, "got", ".", offset);
2358 i += offset + 4 - 1;
2363 char *direct_call_target;
2365 if (!is_got_patch (patch_info->type))
2369 * If this patch is a call, try emitting a direct call instead of
2370 * through a PLT entry. This is possible if the called method is in
2371 * the same assembly and requires no initialization.
2373 direct_call_target = NULL;
2374 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
2375 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2377 if (!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)) {
2378 //printf ("DIRECT: %s %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (callee_cfg->method, TRUE));
2379 direct_call_target = g_strdup_printf (".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
2380 patch_info->type = MONO_PATCH_INFO_NONE;
2381 acfg->stats.direct_calls ++;
2385 acfg->stats.all_calls ++;
2388 if (!got_only && !direct_call_target) {
2389 int plt_offset = get_plt_offset (acfg, patch_info);
2390 if (plt_offset != -1) {
2391 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2392 direct_call_target = g_strdup_printf (".Lp_%d", plt_offset);
2394 /* Nullify the patch */
2395 patch_info->type = MONO_PATCH_INFO_NONE;
2399 if (direct_call_target) {
2400 #if defined(__i386__) || defined(__x86_64__)
2401 g_assert (code [i] == 0xe8);
2402 /* Need to make sure this is exactly 5 bytes long */
2403 emit_byte (acfg, '\xe8');
2404 emit_symbol_diff (acfg, direct_call_target, ".", -4);
2406 #elif defined(__arm__)
2407 #ifdef USE_BIN_WRITER
2408 /* FIXME: Can't encode this using the current symbol writer functions */
2409 g_assert_not_reached ();
2411 emit_unset_mode (acfg);
2412 fprintf (acfg->fp, "bl %s\n", direct_call_target);
2417 g_free (direct_call_target);
2419 got_slot = get_got_offset (acfg, patch_info);
2421 emit_bytes (acfg, code + i, mono_arch_get_patch_offset (code + i));
2423 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
2424 #elif defined(__i386__)
2425 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
2426 #elif defined(__arm__)
2427 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
2429 g_assert_not_reached ();
2432 i += mono_arch_get_patch_offset (code + i) + 4 - 1;
2438 #endif /* MONO_ARCH_AOT_SUPPORTED */
2441 emit_bytes (acfg, code + i, 1);
2446 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2452 int func_alignment = 16;
2453 MonoMethodHeader *header;
2455 method = cfg->orig_method;
2456 code = cfg->native_code;
2457 header = mono_method_get_header (method);
2459 method_index = get_method_index (acfg, method);
2461 /* Make the labels local */
2462 symbol = g_strdup_printf (".Lm_%x", method_index);
2464 emit_alignment (acfg, func_alignment);
2465 emit_label (acfg, symbol);
2466 if (acfg->aot_opts.write_symbols)
2467 emit_global (acfg, symbol, TRUE);
2469 if (cfg->verbose_level > 0)
2470 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2473 acfg->stats.code_size += cfg->code_len;
2475 acfg->method_got_offsets [method_index] = acfg->got_offset;
2477 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2485 * Encode PATCH_INFO into its disk representation.
2488 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2492 switch (patch_info->type) {
2493 case MONO_PATCH_INFO_NONE:
2495 case MONO_PATCH_INFO_IMAGE:
2496 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2498 case MONO_PATCH_INFO_METHOD_REL:
2499 encode_value ((gint)patch_info->data.offset, p, &p);
2501 case MONO_PATCH_INFO_SWITCH: {
2502 gpointer *table = (gpointer *)patch_info->data.table->table;
2505 encode_value (patch_info->data.table->table_size, p, &p);
2506 for (k = 0; k < patch_info->data.table->table_size; k++)
2507 encode_value ((int)(gssize)table [k], p, &p);
2510 case MONO_PATCH_INFO_METHODCONST:
2511 case MONO_PATCH_INFO_METHOD:
2512 case MONO_PATCH_INFO_METHOD_JUMP:
2513 case MONO_PATCH_INFO_ICALL_ADDR:
2514 case MONO_PATCH_INFO_METHOD_RGCTX:
2515 encode_method_ref (acfg, patch_info->data.method, p, &p);
2517 case MONO_PATCH_INFO_INTERNAL_METHOD:
2518 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2519 guint32 len = strlen (patch_info->data.name);
2521 encode_value (len, p, &p);
2523 memcpy (p, patch_info->data.name, len);
2528 case MONO_PATCH_INFO_LDSTR: {
2529 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2530 guint32 token = patch_info->data.token->token;
2531 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2532 encode_value (image_index, p, &p);
2533 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2536 case MONO_PATCH_INFO_RVA:
2537 case MONO_PATCH_INFO_DECLSEC:
2538 case MONO_PATCH_INFO_LDTOKEN:
2539 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2540 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2541 encode_value (patch_info->data.token->token, p, &p);
2543 case MONO_PATCH_INFO_EXC_NAME: {
2544 MonoClass *ex_class;
2547 mono_class_from_name (mono_defaults.exception_class->image,
2548 "System", patch_info->data.target);
2549 g_assert (ex_class);
2550 encode_klass_ref (acfg, ex_class, p, &p);
2553 case MONO_PATCH_INFO_R4:
2554 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2556 case MONO_PATCH_INFO_R8:
2557 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2558 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2560 case MONO_PATCH_INFO_VTABLE:
2561 case MONO_PATCH_INFO_CLASS:
2562 case MONO_PATCH_INFO_IID:
2563 case MONO_PATCH_INFO_ADJUSTED_IID:
2564 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2566 case MONO_PATCH_INFO_CLASS_INIT:
2567 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2568 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2570 case MONO_PATCH_INFO_FIELD:
2571 case MONO_PATCH_INFO_SFLDA:
2572 encode_field_info (acfg, patch_info->data.field, p, &p);
2574 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2576 case MONO_PATCH_INFO_RGCTX_FETCH: {
2577 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2579 encode_method_ref (acfg, entry->method, p, &p);
2580 encode_value (entry->in_mrgctx, p, &p);
2581 encode_value (entry->info_type, p, &p);
2582 encode_value (entry->data->type, p, &p);
2583 encode_patch (acfg, entry->data, p, &p);
2586 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2589 g_warning ("unable to handle jump info %d", patch_info->type);
2590 g_assert_not_reached ();
2597 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2600 guint32 last_offset, j, pindex;
2601 MonoJumpInfo *patch_info;
2603 encode_value (n_patches, p, &p);
2606 encode_value (first_got_offset, p, &p);
2608 /* First encode the type+position table */
2611 for (pindex = 0; pindex < patches->len; ++pindex) {
2613 patch_info = g_ptr_array_index (patches, pindex);
2615 if (patch_info->type == MONO_PATCH_INFO_NONE)
2620 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
2621 offset = patch_info->ip.i - last_offset;
2622 last_offset = patch_info->ip.i;
2624 /* Only the type is needed */
2625 *p = patch_info->type;
2629 /* Then encode the other info */
2630 for (pindex = 0; pindex < patches->len; ++pindex) {
2631 patch_info = g_ptr_array_index (patches, pindex);
2633 if (is_shared_got_patch (patch_info)) {
2634 guint32 offset = get_got_offset (acfg, patch_info);
2635 encode_value (offset, p, &p);
2637 encode_patch (acfg, patch_info, p, &p);
2645 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2649 int pindex, buf_size, n_patches;
2653 MonoJumpInfo *patch_info;
2654 MonoMethodHeader *header;
2655 guint32 method_index;
2657 guint32 first_got_offset;
2659 method = cfg->orig_method;
2660 code = cfg->native_code;
2661 header = mono_method_get_header (method);
2663 method_index = get_method_index (acfg, method);
2665 /* Make the labels local */
2666 symbol = g_strdup_printf (".Lm_%x_p", method_index);
2668 /* Sort relocations */
2669 patches = g_ptr_array_new ();
2670 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2671 g_ptr_array_add (patches, patch_info);
2672 g_ptr_array_sort (patches, compare_patches);
2674 first_got_offset = acfg->method_got_offsets [method_index];
2676 /**********************/
2677 /* Encode method info */
2678 /**********************/
2680 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2681 p = buf = g_malloc (buf_size);
2683 if (mono_class_get_cctor (method->klass))
2684 encode_klass_ref (acfg, method->klass, p, &p);
2686 /* Not needed when loading the method */
2687 encode_value (0, p, &p);
2690 if (cfg->opt & MONO_OPT_SHARED) {
2691 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2692 for (l = cfg->ldstr_list; l; l = l->next) {
2693 encode_value ((long)l->data, p, &p);
2697 /* Used only in shared mode */
2698 g_assert (!cfg->ldstr_list);
2701 for (pindex = 0; pindex < patches->len; ++pindex) {
2702 patch_info = g_ptr_array_index (patches, pindex);
2704 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2705 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2706 patch_info->type = MONO_PATCH_INFO_NONE;
2711 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2712 /* Stored in a GOT slot initialized at module load time */
2713 patch_info->type = MONO_PATCH_INFO_NONE;
2717 if (is_plt_patch (patch_info)) {
2718 /* Calls are made through the PLT */
2719 patch_info->type = MONO_PATCH_INFO_NONE;
2727 g_assert (cfg->has_got_slots);
2729 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2731 acfg->stats.info_size += p - buf;
2733 /* Emit method info */
2735 emit_label (acfg, symbol);
2738 g_assert (p - buf < buf_size);
2739 emit_bytes (acfg, buf, p - buf);
2744 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2747 int k, buf_size, method_index;
2748 guint32 debug_info_size;
2751 MonoMethodHeader *header;
2752 guint8 *p, *buf, *debug_info;
2753 MonoJitInfo *jinfo = cfg->jit_info;
2755 method = cfg->orig_method;
2756 code = cfg->native_code;
2757 header = mono_method_get_header (method);
2759 method_index = get_method_index (acfg, method);
2761 /* Make the labels local */
2762 symbol = g_strdup_printf (".Le_%x_p", method_index);
2764 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2766 buf_size = header->num_clauses * 256 + debug_info_size + 128;
2767 p = buf = g_malloc (buf_size);
2769 encode_value (jinfo->code_size, p, &p);
2770 encode_value (jinfo->used_regs, p, &p);
2771 encode_value (jinfo->has_generic_jit_info, p, &p);
2773 /* Exception table */
2774 if (header->num_clauses) {
2775 for (k = 0; k < header->num_clauses; ++k) {
2776 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2778 encode_value (ei->exvar_offset, p, &p);
2780 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2781 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2783 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2784 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2785 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2789 if (jinfo->has_generic_jit_info) {
2790 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2792 encode_value (gi->has_this ? 1 : 0, p, &p);
2793 encode_value (gi->this_reg, p, &p);
2794 encode_value (gi->this_offset, p, &p);
2797 * Need to encode jinfo->method too, since it is not equal to 'method'
2798 * when using generic sharing.
2800 encode_method_ref (acfg, jinfo->method, p, &p);
2803 g_assert (debug_info_size < buf_size);
2805 encode_value (debug_info_size, p, &p);
2806 if (debug_info_size) {
2807 memcpy (p, debug_info, debug_info_size);
2808 p += debug_info_size;
2809 g_free (debug_info);
2812 acfg->stats.ex_info_size += p - buf;
2816 emit_label (acfg, symbol);
2819 g_assert (p - buf < buf_size);
2820 emit_bytes (acfg, buf, p - buf);
2825 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2827 MonoClass *klass = mono_class_get (acfg->image, token);
2831 gboolean no_special_static, cant_encode;
2832 gpointer iter = NULL;
2834 buf_size = 10240 + (klass->vtable_size * 16);
2835 p = buf = g_malloc (buf_size);
2839 mono_class_init (klass);
2841 mono_class_get_nested_types (klass, &iter);
2842 g_assert (klass->nested_classes_inited);
2844 mono_class_setup_vtable (klass);
2847 * Emit all the information which is required for creating vtables so
2848 * the runtime does not need to create the MonoMethod structures which
2849 * take up a lot of space.
2852 no_special_static = !mono_class_has_special_static_fields (klass);
2854 /* Check whenever we have enough info to encode the vtable */
2855 cant_encode = FALSE;
2856 for (i = 0; i < klass->vtable_size; ++i) {
2857 MonoMethod *cm = klass->vtable [i];
2859 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
2863 if (klass->generic_container || cant_encode) {
2864 encode_value (-1, p, &p);
2866 encode_value (klass->vtable_size, p, &p);
2867 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);
2868 if (klass->has_cctor)
2869 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2870 if (klass->has_finalize)
2871 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2873 encode_value (klass->instance_size, p, &p);
2874 encode_value (mono_class_data_size (klass), p, &p);
2875 encode_value (klass->packing_size, p, &p);
2876 encode_value (klass->min_align, p, &p);
2878 for (i = 0; i < klass->vtable_size; ++i) {
2879 MonoMethod *cm = klass->vtable [i];
2882 encode_method_ref (acfg, cm, p, &p);
2884 encode_value (0, p, &p);
2888 acfg->stats.class_info_size += p - buf;
2891 symbol = g_strdup_printf (".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2892 emit_label (acfg, symbol);
2895 g_assert (p - buf < buf_size);
2896 emit_bytes (acfg, buf, p - buf);
2901 * Calls made from AOTed code are routed through a table of jumps similar to the
2902 * ELF PLT (Program Linkage Table). The differences are the following:
2903 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2904 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2905 * jumps. This means the jumps need to be patched when the address of the callee is
2906 * known. Initially the PLT entries jump to code which transfers control to the
2907 * AOT runtime through the first PLT entry.
2910 emit_plt (MonoAotCompile *acfg)
2915 guint32 *plt_info_offsets;
2918 * Encode info need to resolve PLT entries.
2920 buf_size = acfg->plt_offset * 128;
2921 p = buf = g_malloc (buf_size);
2923 plt_info_offsets = g_new0 (guint32, acfg->plt_offset);
2925 for (i = 1; i < acfg->plt_offset; ++i) {
2926 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
2928 plt_info_offsets [i] = p - buf;
2929 encode_value (patch_info->type, p, &p);
2930 encode_patch (acfg, patch_info, p, &p);
2934 symbol = g_strdup_printf ("plt");
2936 /* This section will be made read-write by the AOT loader */
2937 emit_section_change (acfg, ".text", 0);
2938 emit_global (acfg, symbol, TRUE);
2939 emit_alignment (acfg, PAGESIZE);
2940 emit_label (acfg, symbol);
2943 #if defined(USE_BIN_WRITER) && defined(__arm__)
2945 g_assert_not_reached ();
2948 for (i = 0; i < acfg->plt_offset; ++i) {
2951 label = g_strdup_printf (".Lp_%d", i);
2952 emit_label (acfg, label);
2956 * The first plt entry is used to transfer code to the AOT loader.
2959 #if defined(__i386__)
2961 /* It is filled up during loading by the AOT loader. */
2962 emit_zero_bytes (acfg, 16);
2964 /* Need to make sure this is 9 bytes long */
2965 emit_byte (acfg, '\xe9');
2966 emit_symbol_diff (acfg, "plt", ".", -4);
2967 emit_int32 (acfg, plt_info_offsets [i]);
2969 #elif defined(__x86_64__)
2971 * We can't emit jumps because they are 32 bits only so they can't be patched.
2972 * So we emit a jump table instead whose entries are patched by the AOT loader to
2973 * point to .Lpd entries. ELF stores these in the GOT too, but we don't, since
2974 * methods with GOT entries can't be called directly.
2975 * We also emit the default PLT code here since the PLT code will not be patched.
2976 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
2978 /* jmpq *<offset>(%rip) */
2979 emit_byte (acfg, '\xff');
2980 emit_byte (acfg, '\x25');
2981 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)) -4);
2982 /* Used by mono_aot_get_plt_info_offset */
2983 emit_int32 (acfg, plt_info_offsets [i]);
2984 #elif defined(__arm__)
2986 * - optimize OP_AOTCONST implementation
2987 * - optimize the PLT entries
2988 * - optimize SWITCH AOT implementation
2989 * - implement IMT support
2991 emit_unset_mode (acfg);
2992 fprintf (acfg->fp, "\tldr ip, [pc, #4]\n");
2993 fprintf (acfg->fp, "\tadd ip, pc, ip\n");
2994 fprintf (acfg->fp, "\tldr pc, [ip, #0]\n");
2995 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)));
2996 /* Used by mono_aot_get_plt_info_offset */
2997 #if defined(__MACH__)
2998 fprintf (acfg->fp, "\n\t.long %d\n", plt_info_offsets [i]);
3000 fprintf (acfg->fp, "\n\t.word %d\n", plt_info_offsets [i]);
3004 g_assert_not_reached ();
3008 g_free (plt_info_offsets);
3010 symbol = g_strdup_printf ("plt_end");
3011 emit_global (acfg, symbol, TRUE);
3012 emit_label (acfg, symbol);
3016 symbol = g_strdup_printf ("plt_info");
3017 emit_global (acfg, symbol, FALSE);
3018 emit_label (acfg, symbol);
3021 g_assert (p - buf < buf_size);
3022 emit_bytes (acfg, buf, p - buf);
3025 symbol = g_strdup_printf ("plt_jump_table_addr");
3026 emit_section_change (acfg, ".data", 0);
3027 emit_global (acfg, symbol, FALSE);
3028 emit_alignment (acfg, 8);
3029 emit_label (acfg, symbol);
3030 emit_pointer (acfg, "plt_jump_table");
3033 symbol = g_strdup_printf ("plt_jump_table_size");
3034 emit_section_change (acfg, ".data", 0);
3035 emit_global (acfg, symbol, FALSE);
3036 emit_alignment (acfg, 8);
3037 emit_label (acfg, symbol);
3038 emit_symbol_diff (acfg, "plt_jump_table_end", "plt_jump_table", 0);
3041 /* Don't make this a global so accesses don't need relocations */
3042 symbol = g_strdup_printf ("plt_jump_table");
3043 emit_section_change (acfg, ".bss", 0);
3044 emit_label (acfg, symbol);
3047 #if defined(__x86_64__) || defined(__arm__)
3048 emit_zero_bytes (acfg, (int)(acfg->plt_offset * sizeof (gpointer)));
3051 symbol = g_strdup_printf ("plt_jump_table_end");
3052 emit_label (acfg, symbol);
3056 static G_GNUC_UNUSED void
3057 emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code,
3058 guint32 code_size, int got_offset, MonoJumpInfo *ji)
3062 MonoJumpInfo *patch_info;
3068 symbol = g_strdup_printf ("%s", name);
3070 emit_section_change (acfg, ".text", 0);
3071 emit_global (acfg, symbol, TRUE);
3072 emit_alignment (acfg, 16);
3073 emit_label (acfg, symbol);
3077 * The code should access everything through the GOT, so we pass
3080 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3084 /* Sort relocations */
3085 patches = g_ptr_array_new ();
3086 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3087 g_ptr_array_add (patches, patch_info);
3088 g_ptr_array_sort (patches, compare_patches);
3090 buf_size = patches->len * 128 + 128;
3091 buf = g_malloc (buf_size);
3094 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3095 g_assert (p - buf < buf_size);
3097 symbol = g_strdup_printf ("%s_p", name);
3099 emit_section_change (acfg, ".text", 0);
3100 emit_global (acfg, symbol, FALSE);
3101 emit_label (acfg, symbol);
3104 emit_bytes (acfg, buf, p - buf);
3108 * When running in aot-only mode, we can't create trampolines at runtime, so we create
3109 * a few, and save them in the AOT file. Normal trampolines embed their argument as a
3110 * literal inside the trampoline code, we can't do that here, so instead we embed an offset
3111 * which needs to be added to the trampoline address to get the address of the GOT slot
3112 * which contains the argument value.
3113 * The generated trampolines jump to the generic trampolines using another GOT slot, which
3114 * will be setup by the AOT loader to point to the generic trampoline code of the given
3118 emit_trampolines (MonoAotCompile *acfg)
3122 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3129 if (!acfg->aot_opts.full_aot)
3132 g_assert (acfg->image->assembly);
3134 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3135 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3136 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3138 * Emit the generic trampolines.
3140 * We could save some code by treating the generic trampolines as a wrapper
3141 * method, but that approach has its own complexities, so we choose the simpler
3144 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3145 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, TRUE);
3147 /* Emit trampoline code */
3149 symbol = g_strdup_printf ("generic_trampoline_%d", tramp_type);
3151 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3156 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3157 emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL);
3159 /* Emit the exception related code pieces */
3160 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3161 emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji);
3162 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3163 emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji);
3164 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3165 emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji);
3166 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3167 emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji);
3168 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3169 emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji);
3170 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3171 emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji);
3174 for (i = 0; i < 128; ++i) {
3177 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3178 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3179 symbol = g_strdup_printf ("rgctx_fetch_trampoline_%u", offset);
3180 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3183 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3184 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3185 symbol = g_strdup_printf ("rgctx_fetch_trampoline_%u", offset);
3186 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3193 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3197 /* Reserve some entries at the end of the GOT for our use */
3198 acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
3200 symbol = g_strdup_printf ("trampolines");
3202 emit_section_change (acfg, ".text", 0);
3203 emit_global (acfg, symbol, TRUE);
3204 emit_alignment (acfg, 16);
3205 emit_label (acfg, symbol);
3207 for (i = 0; i < acfg->num_aot_trampolines; ++i) {
3208 offset = acfg->got_offset + (i * 2);
3211 * The trampolines created here are variations of the specific
3212 * trampolines created in mono_arch_create_specific_trampoline (). The
3214 * - the generic trampoline address is taken from a got slot.
3215 * - the offset of the got slot where the trampoline argument is stored
3216 * is embedded in the instruction stream, and the generic trampoline
3217 * can load the argument by loading the offset, adding it to the
3218 * address of the trampoline to get the address of the got slot, and
3219 * loading the argument from the there.
3221 #if defined(__x86_64__)
3222 /* This should be exactly 16 bytes long */
3223 /* It should work together with the generic trampoline code in tramp-amd64.c */
3224 /* call *<offset>(%rip) */
3225 emit_byte (acfg, '\x41');
3226 emit_byte (acfg, '\xff');
3227 emit_byte (acfg, '\x15');
3228 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
3229 /* This should be relative to the start of the trampoline */
3230 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
3231 emit_zero_bytes (acfg, 5);
3232 #elif defined(__arm__)
3236 /* Generate the trampoline code */
3237 /* This should be exactly 28 bytes long */
3240 ARM_PUSH (code, 0x5fff);
3241 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
3242 /* Load the value from the GOT */
3243 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
3245 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
3246 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
3248 g_assert (code - buf == 20);
3251 emit_bytes (acfg, buf, code - buf);
3252 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
3253 emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
3256 g_assert_not_reached ();
3261 /* Unbox trampolines */
3263 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3265 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3269 method = mono_get_method (acfg->image, token, NULL);
3271 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3272 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
3275 symbol = g_strdup_printf ("unbox_trampoline_%d", i);
3277 emit_section_change (acfg, ".text", 0);
3278 emit_global (acfg, symbol, TRUE);
3279 emit_label (acfg, symbol);
3281 call_target = g_strdup_printf (".Lm_%x", get_method_index (acfg, cfg->orig_method));
3283 #if defined(__x86_64__)
3288 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (cfg->orig_method), cfg->generic_sharing_context, NULL);
3290 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
3292 emit_bytes (acfg, buf, code - buf);
3294 emit_byte (acfg, '\xe9');
3295 emit_symbol_diff (acfg, call_target, ".", -4);
3297 #elif defined(__arm__)
3304 if (MONO_TYPE_ISSTRUCT (mono_method_signature (cfg->orig_method)->ret))
3307 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
3309 emit_bytes (acfg, buf, code - buf);
3310 /* jump to method */
3311 #if defined(USE_BIN_WRITER)
3313 g_assert_not_reached ();
3315 fprintf (acfg->fp, "\n\tb %s\n", call_target);
3318 g_assert_not_reached ();
3322 symbol = g_strdup_printf ("trampolines_info");
3324 emit_section_change (acfg, ".text", 0);
3325 emit_global (acfg, symbol, TRUE);
3326 emit_alignment (acfg, PAGESIZE);
3327 emit_label (acfg, symbol);
3329 emit_int32 (acfg, acfg->num_aot_trampolines);
3330 emit_int32 (acfg, acfg->got_offset);
3334 str_begins_with (const char *str1, const char *str2)
3336 int len = strlen (str2);
3337 return strncmp (str1, str2, len) == 0;
3341 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3343 gchar **args, **ptr;
3345 memset (opts, 0, sizeof (*opts));
3347 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3348 for (ptr = args; ptr && *ptr; ptr ++) {
3349 const char *arg = *ptr;
3351 if (str_begins_with (arg, "outfile=")) {
3352 opts->outfile = g_strdup (arg + strlen ("outfile="));
3353 } else if (str_begins_with (arg, "save-temps")) {
3354 opts->save_temps = TRUE;
3355 } else if (str_begins_with (arg, "keep-temps")) {
3356 opts->save_temps = TRUE;
3357 } else if (str_begins_with (arg, "write-symbols")) {
3358 opts->write_symbols = TRUE;
3359 } else if (str_begins_with (arg, "metadata-only")) {
3360 opts->metadata_only = TRUE;
3361 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3362 opts->bind_to_runtime_version = TRUE;
3363 } else if (str_begins_with (arg, "full")) {
3364 opts->full_aot = TRUE;
3366 * The no-dlsym option is only useful on the iphone, and even there,
3367 * do to other limitations of the dynamic linker, it doesn't seem to
3368 * work. So disable it for now so we don't have to support it.
3371 } else if (str_begins_with (arg, "no-dlsym")) {
3372 opts->no_dlsym = TRUE;
3374 } else if (str_begins_with (arg, "static")) {
3375 opts->static_link = TRUE;
3376 opts->no_dlsym = TRUE;
3377 } else if (str_begins_with (arg, "asmonly")) {
3378 opts->asm_only = TRUE;
3380 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3389 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3391 MonoMethod *method = (MonoMethod*)key;
3392 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3393 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3394 MonoAotCompile *acfg = user_data;
3396 new_ji->image = ji->image;
3397 new_ji->token = ji->token;
3398 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3402 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3405 MonoJumpInfo *patch_info;
3408 MonoMethod *wrapped;
3410 if (acfg->aot_opts.metadata_only)
3413 index = get_method_index (acfg, method);
3415 /* fixme: maybe we can also precompile wrapper methods */
3416 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3417 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3418 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3419 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3423 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3426 wrapped = mono_marshal_method_from_wrapper (method);
3427 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3428 // FIXME: The wrapper should be generic too, but it is not
3431 acfg->stats.mcount++;
3433 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3435 * FIXME: Enabling this causes virtual-sync.exe to fail, since the trampoline
3436 * code can't determine that it needs to insert a sync wrapper in the AOT case.
3442 if (method->is_generic || method->klass->generic_container) {
3443 acfg->stats.genericcount ++;
3448 if (acfg->aot_opts.full_aot)
3449 mono_use_imt = FALSE;
3452 * Since these methods are the only ones which are compiled with
3453 * AOT support, and they are not used by runtime startup/shutdown code,
3454 * the runtime will not see AOT methods during AOT compilation,so it
3455 * does not need to support them by creating a fake GOT etc.
3457 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3458 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3459 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3460 acfg->stats.genericcount ++;
3463 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3464 /* Let the exception happen at runtime */
3468 if (cfg->disable_aot) {
3469 //printf ("Skip (other): %s\n", mono_method_full_name (method, TRUE));
3470 acfg->stats.ocount++;
3471 mono_destroy_compile (cfg);
3475 /* Nullify patches which need no aot processing */
3476 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3477 switch (patch_info->type) {
3478 case MONO_PATCH_INFO_LABEL:
3479 case MONO_PATCH_INFO_BB:
3480 patch_info->type = MONO_PATCH_INFO_NONE;
3487 /* Collect method->token associations from the cfg */
3488 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3491 * Check for absolute addresses.
3494 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3495 switch (patch_info->type) {
3496 case MONO_PATCH_INFO_ABS:
3497 /* unable to handle this */
3498 //printf ("Skip (abs addr): %s %d\n", mono_method_full_name (method, TRUE), patch_info->type);
3507 acfg->stats.abscount++;
3508 mono_destroy_compile (cfg);
3513 * Check for wrapper methods we can't encode.
3516 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3517 if ((patch_info->type == MONO_PATCH_INFO_METHODCONST) || (patch_info->type == MONO_PATCH_INFO_METHOD)) {
3518 switch (patch_info->data.method->wrapper_type) {
3519 case MONO_WRAPPER_NONE:
3520 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3521 case MONO_WRAPPER_XDOMAIN_INVOKE:
3522 case MONO_WRAPPER_STFLD:
3523 case MONO_WRAPPER_LDFLD:
3524 case MONO_WRAPPER_LDFLDA:
3525 case MONO_WRAPPER_LDFLD_REMOTE:
3526 case MONO_WRAPPER_STFLD_REMOTE:
3527 case MONO_WRAPPER_STELEMREF:
3528 case MONO_WRAPPER_ISINST:
3529 case MONO_WRAPPER_PROXY_ISINST:
3530 case MONO_WRAPPER_ALLOC:
3531 case MONO_WRAPPER_REMOTING_INVOKE:
3532 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
3535 /* unable to handle this */
3536 //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));
3540 } else if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH) {
3541 MonoJumpInfo *child = patch_info->data.rgctx_entry->data;
3543 if (child->type == MONO_PATCH_INFO_METHODCONST) {
3544 switch (child->data.method->wrapper_type) {
3545 case MONO_WRAPPER_NONE:
3546 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
3556 acfg->stats.wrappercount++;
3557 mono_destroy_compile (cfg);
3562 * Check for methods/klasses we can't encode.
3565 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3566 switch (patch_info->type) {
3567 case MONO_PATCH_INFO_METHOD:
3568 case MONO_PATCH_INFO_METHODCONST:
3569 if (patch_info->data.method->wrapper_type)
3571 if (!patch_info->data.method->token) {
3572 /* The method is part of a constructed type like Int[,].Set (). */
3573 if (!g_hash_table_lookup (acfg->token_info_hash, patch_info->data.method))
3577 case MONO_PATCH_INFO_VTABLE:
3578 case MONO_PATCH_INFO_CLASS_INIT:
3579 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3580 case MONO_PATCH_INFO_CLASS:
3581 case MONO_PATCH_INFO_IID:
3582 case MONO_PATCH_INFO_ADJUSTED_IID:
3583 if (!patch_info->data.klass->type_token)
3584 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))
3593 acfg->stats.ocount++;
3594 mono_destroy_compile (cfg);
3598 /* Determine whenever the method has GOT slots */
3599 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3600 switch (patch_info->type) {
3601 case MONO_PATCH_INFO_GOT_OFFSET:
3602 case MONO_PATCH_INFO_NONE:
3604 case MONO_PATCH_INFO_IMAGE:
3605 /* The assembly is stored in GOT slot 0 */
3606 if (patch_info->data.image != acfg->image)
3607 cfg->has_got_slots = TRUE;
3610 if (!is_plt_patch (patch_info))
3611 cfg->has_got_slots = TRUE;
3616 if (!cfg->has_got_slots)
3617 acfg->stats.methods_without_got_slots ++;
3619 /* Make a copy of the patch info which is in the mempool */
3621 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3623 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3624 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3627 patches = new_patch_info;
3629 patches_end->next = new_patch_info;
3630 patches_end = new_patch_info;
3632 cfg->patch_info = patches;
3635 /* Free some fields used by cfg to conserve memory */
3636 mono_mempool_destroy (cfg->mempool);
3637 cfg->mempool = NULL;
3638 g_free (cfg->varinfo);
3639 cfg->varinfo = NULL;
3643 mono_regstate_free (cfg->rs);
3647 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
3649 acfg->cfgs [index] = cfg;
3651 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3653 acfg->stats.ccount++;
3657 load_profile_files (MonoAotCompile *acfg)
3661 int file_index, res, method_index, i;
3668 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);
3670 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3675 infile = fopen (tmp, "r");
3678 printf ("Using profile data file '%s'\n", tmp);
3683 res = fscanf (infile, "%32s\n", ver);
3684 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3685 printf ("Profile file has wrong version or invalid.\n");
3691 res = fscanf (infile, "%d\n", &token);
3695 method_index = mono_metadata_token_index (token) - 1;
3697 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3698 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3703 /* Add missing methods */
3705 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3706 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3707 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3709 unordered = g_list_reverse (unordered);
3710 if (acfg->method_order)
3711 g_list_last (acfg->method_order)->next = unordered;
3713 acfg->method_order = unordered;
3719 * Collect all patches which have shared GOT entries and alloc entries for them. The
3720 * rest will get entries allocated during emit_code ().
3723 alloc_got_slots (MonoAotCompile *acfg)
3729 /* Slot 0 is reserved for the address of the current assembly */
3730 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3731 ji->type = MONO_PATCH_INFO_IMAGE;
3732 ji->data.image = acfg->image;
3734 get_shared_got_offset (acfg, ji);
3736 for (l = acfg->method_order; l != NULL; l = l->next) {
3737 i = GPOINTER_TO_UINT (l->data);
3739 if (acfg->cfgs [i]) {
3740 MonoCompile *cfg = acfg->cfgs [i];
3742 for (ji = cfg->patch_info; ji; ji = ji->next) {
3743 if (is_shared_got_patch (ji))
3744 get_shared_got_offset (acfg, ji);
3751 emit_code (MonoAotCompile *acfg)
3757 symbol = g_strdup_printf ("methods");
3758 emit_section_change (acfg, ".text", 0);
3759 emit_global (acfg, symbol, TRUE);
3760 emit_alignment (acfg, 8);
3761 emit_label (acfg, symbol);
3764 for (l = acfg->method_order; l != NULL; l = l->next) {
3765 i = GPOINTER_TO_UINT (l->data);
3768 emit_method_code (acfg, acfg->cfgs [i]);
3771 symbol = g_strdup_printf ("methods_end");
3772 emit_section_change (acfg, ".text", 0);
3773 emit_global (acfg, symbol, FALSE);
3774 emit_alignment (acfg, 8);
3775 emit_label (acfg, symbol);
3778 symbol = g_strdup_printf ("method_offsets");
3779 emit_section_change (acfg, ".text", 1);
3780 emit_global (acfg, symbol, FALSE);
3781 emit_alignment (acfg, 8);
3782 emit_label (acfg, symbol);
3785 for (i = 0; i < acfg->nmethods; ++i) {
3786 if (acfg->cfgs [i]) {
3787 symbol = g_strdup_printf (".Lm_%x", i);
3788 emit_symbol_diff (acfg, symbol, "methods", 0);
3791 emit_int32 (acfg, 0xffffffff);
3798 emit_info (MonoAotCompile *acfg)
3804 /* Emit method info */
3805 symbol = g_strdup_printf ("method_info");
3806 emit_section_change (acfg, ".text", 1);
3807 emit_global (acfg, symbol, FALSE);
3808 emit_alignment (acfg, 8);
3809 emit_label (acfg, symbol);
3812 /* To reduce size of generated assembly code */
3813 symbol = g_strdup_printf ("mi");
3814 emit_label (acfg, symbol);
3817 for (l = acfg->method_order; l != NULL; l = l->next) {
3818 i = GPOINTER_TO_UINT (l->data);
3821 emit_method_info (acfg, acfg->cfgs [i]);
3824 symbol = g_strdup_printf ("method_info_offsets");
3825 emit_section_change (acfg, ".text", 1);
3826 emit_global (acfg, symbol, FALSE);
3827 emit_alignment (acfg, 8);
3828 emit_label (acfg, symbol);
3831 for (i = 0; i < acfg->nmethods; ++i) {
3832 if (acfg->cfgs [i]) {
3833 symbol = g_strdup_printf (".Lm_%x_p", i);
3834 emit_symbol_diff (acfg, symbol, "mi", 0);
3837 emit_int32 (acfg, 0);
3844 emit_wrapper_info (MonoAotCompile *acfg)
3850 /* Emit method info */
3851 symbol = g_strdup_printf ("wrapper_info");
3852 emit_section_change (acfg, ".text", 1);
3853 emit_global (acfg, symbol, FALSE);
3854 emit_alignment (acfg, 8);
3855 emit_label (acfg, symbol);
3858 if (!acfg->aot_opts.full_aot)
3861 for (i = 0; i < acfg->nmethods; ++i) {
3862 MonoCompile *cfg = acfg->cfgs [i];
3865 if (!cfg || !cfg->orig_method->wrapper_type)
3868 method = cfg->orig_method;
3869 index = get_method_index (acfg, method);
3871 // FIXME: Optimize disk usage and lookup speed
3872 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
3873 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3874 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
3877 name = mono_method_full_name (cfg->orig_method, TRUE);
3879 emit_string (acfg, name);
3880 emit_alignment (acfg, 4);
3881 emit_int32 (acfg, index);
3884 emit_byte (acfg, 0);
3890 emit_method_order (MonoAotCompile *acfg)
3896 symbol = g_strdup_printf ("method_order");
3897 emit_section_change (acfg, ".text", 1);
3898 emit_global (acfg, symbol, FALSE);
3899 emit_alignment (acfg, 8);
3900 emit_label (acfg, symbol);
3903 /* First emit an index table */
3906 for (l = acfg->method_order; l != NULL; l = l->next) {
3907 i = GPOINTER_TO_UINT (l->data);
3909 if (acfg->cfgs [i]) {
3910 if ((index % 1024) == 0) {
3911 emit_int32 (acfg, i);
3919 emit_int32 (acfg, 0xffffff);
3921 /* Then emit the whole method order */
3922 for (l = acfg->method_order; l != NULL; l = l->next) {
3923 i = GPOINTER_TO_UINT (l->data);
3925 if (acfg->cfgs [i]) {
3926 emit_int32 (acfg, i);
3931 symbol = g_strdup_printf ("method_order_end");
3932 emit_section_change (acfg, ".text", 1);
3933 emit_global (acfg, symbol, FALSE);
3934 emit_label (acfg, symbol);
3939 emit_exception_info (MonoAotCompile *acfg)
3944 symbol = g_strdup_printf ("ex_info");
3945 emit_section_change (acfg, ".text", 1);
3946 emit_global (acfg, symbol, FALSE);
3947 emit_alignment (acfg, 8);
3948 emit_label (acfg, symbol);
3951 /* To reduce size of generated assembly */
3952 symbol = g_strdup_printf ("ex");
3953 emit_label (acfg, symbol);
3956 for (i = 0; i < acfg->nmethods; ++i) {
3958 emit_exception_debug_info (acfg, acfg->cfgs [i]);
3961 symbol = g_strdup_printf ("ex_info_offsets");
3962 emit_section_change (acfg, ".text", 1);
3963 emit_global (acfg, symbol, FALSE);
3964 emit_alignment (acfg, 8);
3965 emit_label (acfg, symbol);
3968 for (i = 0; i < acfg->nmethods; ++i) {
3969 if (acfg->cfgs [i]) {
3970 symbol = g_strdup_printf (".Le_%x_p", i);
3971 emit_symbol_diff (acfg, symbol, "ex", 0);
3974 emit_int32 (acfg, 0);
3981 emit_class_info (MonoAotCompile *acfg)
3986 symbol = g_strdup_printf ("class_info");
3987 emit_section_change (acfg, ".text", 1);
3988 emit_global (acfg, symbol, FALSE);
3989 emit_alignment (acfg, 8);
3990 emit_label (acfg, symbol);
3993 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
3994 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
3996 symbol = g_strdup_printf ("class_info_offsets");
3997 emit_section_change (acfg, ".text", 1);
3998 emit_global (acfg, symbol, FALSE);
3999 emit_alignment (acfg, 8);
4000 emit_label (acfg, symbol);
4003 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4004 symbol = g_strdup_printf (".LK_I_%x", i);
4005 emit_symbol_diff (acfg, symbol, "class_info", 0);
4011 typedef struct ClassNameTableEntry {
4012 guint32 token, index;
4013 struct ClassNameTableEntry *next;
4014 } ClassNameTableEntry;
4017 emit_class_name_table (MonoAotCompile *acfg)
4020 guint32 token, hash;
4025 ClassNameTableEntry *entry, *new_entry;
4028 * Construct a chained hash table for mapping class names to typedef tokens.
4030 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4031 table = g_ptr_array_sized_new (table_size);
4032 for (i = 0; i < table_size; ++i)
4033 g_ptr_array_add (table, NULL);
4034 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4035 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4036 klass = mono_class_get (acfg->image, token);
4037 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4038 hash = g_str_hash (full_name) % table_size;
4041 /* FIXME: Allocate from the mempool */
4042 new_entry = g_new0 (ClassNameTableEntry, 1);
4043 new_entry->token = token;
4045 entry = g_ptr_array_index (table, hash);
4046 if (entry == NULL) {
4047 new_entry->index = hash;
4048 g_ptr_array_index (table, hash) = new_entry;
4051 entry = entry->next;
4053 entry->next = new_entry;
4054 new_entry->index = table->len;
4055 g_ptr_array_add (table, new_entry);
4059 /* Emit the table */
4060 symbol = g_strdup_printf ("class_name_table");
4061 emit_section_change (acfg, ".text", 0);
4062 emit_global (acfg, symbol, FALSE);
4063 emit_alignment (acfg, 8);
4064 emit_label (acfg, symbol);
4067 /* FIXME: Optimize memory usage */
4068 g_assert (table_size < 65000);
4069 emit_int16 (acfg, table_size);
4070 g_assert (table->len < 65000);
4071 for (i = 0; i < table->len; ++i) {
4072 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4074 if (entry == NULL) {
4075 emit_int16 (acfg, 0);
4076 emit_int16 (acfg, 0);
4078 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4080 emit_int16 (acfg, entry->next->index);
4082 emit_int16 (acfg, 0);
4088 emit_image_table (MonoAotCompile *acfg)
4094 * The image table is small but referenced in a lot of places.
4095 * So we emit it at once, and reference its elements by an index.
4098 symbol = g_strdup_printf ("mono_image_table");
4099 emit_section_change (acfg, ".text", 1);
4100 emit_global (acfg, symbol, FALSE);
4101 emit_alignment (acfg, 8);
4102 emit_label (acfg, symbol);
4105 emit_int32 (acfg, acfg->image_table->len);
4106 for (i = 0; i < acfg->image_table->len; i++) {
4107 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4108 MonoAssemblyName *aname = &image->assembly->aname;
4110 /* FIXME: Support multi-module assemblies */
4111 g_assert (image->assembly->image == image);
4113 emit_string (acfg, image->assembly_name);
4114 emit_string (acfg, image->guid);
4115 emit_string (acfg, aname->culture ? aname->culture : "");
4116 emit_string (acfg, (const char*)aname->public_key_token);
4118 emit_alignment (acfg, 8);
4119 emit_int32 (acfg, aname->flags);
4120 emit_int32 (acfg, aname->major);
4121 emit_int32 (acfg, aname->minor);
4122 emit_int32 (acfg, aname->build);
4123 emit_int32 (acfg, aname->revision);
4128 emit_got_info (MonoAotCompile *acfg)
4133 guint32 *got_info_offsets;
4137 * - optimize offsets table.
4138 * - reduce number of exported symbols.
4139 * - emit info for a klass only once.
4140 * - determine when a method uses a GOT slot which is guaranteed to be already
4142 * - clean up and document the code.
4143 * - use String.Empty in class libs.
4146 /* Encode info required to decode shared GOT entries */
4147 buf_size = acfg->shared_patches->len * 64;
4148 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4149 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
4150 for (i = 0; i < acfg->shared_patches->len; ++i) {
4151 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
4153 /* No need to encode the patch type */
4154 got_info_offsets [i] = p - buf;
4155 encode_patch (acfg, ji, p, &p);
4158 g_assert (p - buf <= buf_size);
4160 acfg->stats.got_info_size = p - buf;
4162 /* Emit got_info table */
4163 symbol = g_strdup_printf ("got_info");
4164 emit_section_change (acfg, ".text", 1);
4165 emit_global (acfg, symbol, FALSE);
4166 emit_alignment (acfg, 8);
4167 emit_label (acfg, symbol);
4170 emit_bytes (acfg, buf, p - buf);
4172 /* Emit got_info_offsets table */
4173 symbol = g_strdup_printf ("got_info_offsets");
4174 emit_section_change (acfg, ".text", 1);
4175 emit_global (acfg, symbol, FALSE);
4176 emit_alignment (acfg, 8);
4177 emit_label (acfg, symbol);
4180 for (i = 0; i < acfg->shared_patches->len; ++i)
4181 emit_int32 (acfg, got_info_offsets [i]);
4183 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
4187 emit_got (MonoAotCompile *acfg)
4191 /* Don't make GOT global so accesses to it don't need relocations */
4192 symbol = g_strdup_printf ("got");
4193 emit_section_change (acfg, ".bss", 1);
4194 emit_alignment (acfg, 8);
4195 emit_label (acfg, symbol);
4196 if ((acfg->got_offset + acfg->num_trampoline_got_entries) > 0)
4197 emit_zero_bytes (acfg, (int)((acfg->got_offset + acfg->num_trampoline_got_entries) * sizeof (gpointer)));
4200 symbol = g_strdup_printf ("got_addr");
4201 emit_section_change (acfg, ".data", 1);
4202 emit_global (acfg, symbol, FALSE);
4203 emit_alignment (acfg, 8);
4204 emit_label (acfg, symbol);
4205 emit_pointer (acfg, "got");
4208 symbol = g_strdup_printf ("got_size");
4209 emit_section_change (acfg, ".data", 1);
4210 emit_global (acfg, symbol, FALSE);
4211 emit_alignment (acfg, 8);
4212 emit_label (acfg, symbol);
4213 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4218 emit_globals (MonoAotCompile *acfg)
4222 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4224 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4226 opts_str = g_strdup_printf ("%d", acfg->opts);
4227 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4230 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4232 if (acfg->aot_opts.bind_to_runtime_version)
4233 emit_string_symbol (acfg, "mono_runtime_version", FULL_VERSION);
4235 emit_string_symbol (acfg, "mono_runtime_version", "");
4238 * Some platforms like the iphone have no working dlsym (). To work around this,
4239 * we create an ELF ctor function which will be invoked by dlopen, and which
4240 * will call a function in the AOT loader to register the symbols used by the
4242 * When static linking, we emit a global which will point to the symbol table.
4244 if (acfg->aot_opts.no_dlsym) {
4248 if (acfg->aot_opts.static_link)
4249 /* Emit a string holding the assembly name */
4250 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4252 /* Emit the names */
4253 for (i = 0; i < acfg->globals->len; ++i) {
4254 char *name = g_ptr_array_index (acfg->globals, i);
4256 symbol = g_strdup_printf ("name_%d", i);
4257 emit_section_change (acfg, ".text", 1);
4258 emit_label (acfg, symbol);
4259 emit_string (acfg, name);
4263 /* Emit the globals table */
4264 symbol = g_strdup_printf ("globals");
4265 emit_section_change (acfg, ".data", 0);
4266 /* This is not a global, since it is accessed by the init function */
4267 emit_alignment (acfg, 8);
4268 emit_label (acfg, symbol);
4270 for (i = 0; i < acfg->globals->len; ++i) {
4271 char *name = g_ptr_array_index (acfg->globals, i);
4273 symbol = g_strdup_printf ("name_%d", i);
4274 emit_pointer (acfg, symbol);
4277 symbol = g_strdup_printf ("%s", name);
4278 emit_pointer (acfg, symbol);
4281 /* Null terminate the table */
4282 emit_pointer (acfg, NULL);
4283 emit_pointer (acfg, NULL);
4285 if (acfg->aot_opts.static_link) {
4289 * Emit a global symbol which can be passed by an embedding app to
4290 * mono_aot_register_module ().
4292 #if defined(__MACH__)
4293 symbol = g_strdup_printf ("_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4295 symbol = g_strdup_printf ("mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4298 /* Get rid of characters which cannot occur in symbols */
4300 for (p = symbol; *p; ++p) {
4301 if (!(isalnum (*p) || *p == '_'))
4304 acfg->static_linking_symbol = g_strdup (symbol);
4305 emit_global_inner (acfg, symbol, FALSE);
4306 emit_alignment (acfg, 8);
4307 emit_label (acfg, symbol);
4308 emit_pointer (acfg, "globals");
4310 symbol = g_strdup_printf ("init_%s", acfg->image->assembly->aname.name);
4311 emit_section_change (acfg, ".text", 1);
4312 emit_alignment (acfg, 8);
4313 emit_label (acfg, symbol);
4314 #ifdef USE_BIN_WRITER
4315 g_assert_not_reached ();
4318 fprintf (acfg->fp, "leaq globals(%%rip), %%rdi\n");
4319 fprintf (acfg->fp, "call mono_aot_register_globals@PLT\n");
4320 fprintf (acfg->fp, "ret\n");
4321 fprintf (acfg->fp, ".section .ctors,\"aw\",@progbits\n");
4322 emit_alignment (acfg, 8);
4323 emit_pointer (acfg, symbol);
4324 #elif defined(__arm__) && defined(__MACH__)
4326 fprintf (acfg->fp, ".text\n");
4327 fprintf (acfg->fp, ".align 3\n");
4329 fprintf (acfg->fp, "ldr r0, .L5\n");
4330 fprintf (acfg->fp, ".LPIC0:\n");
4331 fprintf (acfg->fp, "add r0, pc, r0\n");
4332 fprintf (acfg->fp, "ldr r0, [r0]\n");
4333 fprintf (acfg->fp, "b _mono_aot_register_globals@PLT\n");
4334 fprintf (acfg->fp, ".align 2\n");
4336 fprintf (acfg->fp, ".L5:\n");
4337 fprintf (acfg->fp, ".long globals_ptr-(.LPIC0+8)\n");
4339 fprintf (acfg->fp, ".data\n");
4340 fprintf (acfg->fp, ".align 2\n");
4341 fprintf (acfg->fp, "globals_ptr:\n");
4342 fprintf (acfg->fp, ".long globals\n");
4344 fprintf (acfg->fp, ".mod_init_func\n");
4345 fprintf (acfg->fp, ".align 2\n");
4346 fprintf (acfg->fp, ".long %s@target1\n", symbol);
4348 #elif defined(__arm__)
4350 * Taken from gcc generated code for:
4352 * void foo () { bar (&i); }
4353 * gcc --shared -fPIC -O2
4355 fprintf (acfg->fp, "ldr r3, .L5\n");
4356 fprintf (acfg->fp, "ldr r0, .L5+4\n");
4357 fprintf (acfg->fp, ".LPIC0:\n");
4358 fprintf (acfg->fp, "add r3, pc, r3\n");
4359 fprintf (acfg->fp, "add r0, r3, r0\n");
4360 fprintf (acfg->fp, "b mono_aot_register_globals(PLT)\n");
4362 fprintf (acfg->fp, ".L5:\n");
4363 fprintf (acfg->fp, ".word _GLOBAL_OFFSET_TABLE_-(.LPIC0+8)\n");
4364 fprintf (acfg->fp, ".word globals(GOTOFF)\n");
4366 fprintf (acfg->fp, ".section .init_array,\"aw\",%%init_array\n");
4367 fprintf (acfg->fp, ".align 2\n");
4368 fprintf (acfg->fp, ".word %s(target1)\n", symbol);
4370 g_assert_not_reached ();
4379 acfg_free (MonoAotCompile *acfg)
4383 for (i = 0; i < acfg->nmethods; ++i)
4385 g_free (acfg->cfgs [i]);
4386 g_free (acfg->cfgs);
4387 g_free (acfg->method_got_offsets);
4388 g_free (acfg->static_linking_symbol);
4389 g_ptr_array_free (acfg->methods, TRUE);
4390 g_ptr_array_free (acfg->shared_patches, TRUE);
4391 g_ptr_array_free (acfg->image_table, TRUE);
4392 g_ptr_array_free (acfg->globals, TRUE);
4393 g_hash_table_destroy (acfg->method_indexes);
4394 g_hash_table_destroy (acfg->plt_offset_to_patch);
4395 g_hash_table_destroy (acfg->patch_to_plt_offset);
4396 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
4397 g_hash_table_destroy (acfg->method_to_cfg);
4398 g_hash_table_destroy (acfg->token_info_hash);
4399 g_hash_table_destroy (acfg->image_hash);
4400 mono_mempool_destroy (acfg->mempool);
4405 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4407 MonoImage *image = ass->image;
4410 MonoAotCompile *acfg;
4412 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4414 acfg = g_new0 (MonoAotCompile, 1);
4415 acfg->methods = g_ptr_array_new ();
4416 acfg->method_indexes = g_hash_table_new (NULL, NULL);
4417 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4418 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4419 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4420 acfg->shared_patches = g_ptr_array_new ();
4421 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4422 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4423 acfg->image_hash = g_hash_table_new (NULL, NULL);
4424 acfg->image_table = g_ptr_array_new ();
4425 acfg->globals = g_ptr_array_new ();
4426 acfg->image = image;
4428 acfg->mempool = mono_mempool_new ();
4430 mono_aot_parse_options (aot_options, &acfg->aot_opts);
4432 load_profile_files (acfg);
4436 acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 10240 : 0;
4438 acfg->method_index = 1;
4440 /* Collect methods */
4441 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4443 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4445 method = mono_get_method (acfg->image, token, NULL);
4447 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4448 /* Compile the wrapper instead */
4449 /* We do this here instead of add_wrappers () because it is easy to do it here */
4450 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4454 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4455 add_method_with_index (acfg, method, i);
4456 acfg->method_index ++;
4459 if (acfg->aot_opts.full_aot)
4460 add_wrappers (acfg);
4462 acfg->nmethods = acfg->methods->len + 1;
4463 acfg->cfgs = g_new0 (MonoCompile*, acfg->nmethods + 32);
4464 acfg->method_got_offsets = g_new0 (guint32, acfg->nmethods + 32);
4466 /* PLT offset 0 is reserved for the PLT trampoline */
4467 acfg->plt_offset = 1;
4469 /* Compile methods */
4470 for (i = 0; i < acfg->methods->len; ++i) {
4471 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4474 alloc_got_slots (acfg);
4480 emit_wrapper_info (acfg);
4482 emit_method_order (acfg);
4484 emit_trampolines (acfg);
4486 emit_class_name_table (acfg);
4488 emit_got_info (acfg);
4490 emit_exception_info (acfg);
4492 emit_class_info (acfg);
4496 emit_image_table (acfg);
4500 emit_globals (acfg);
4502 symbol = g_strdup_printf ("mem_end");
4503 emit_section_change (acfg, ".text", 1);
4504 emit_global (acfg, symbol, FALSE);
4505 emit_alignment (acfg, 8);
4506 emit_label (acfg, symbol);
4509 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)));
4511 res = emit_writeout (acfg);
4517 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);
4518 if (acfg->stats.genericcount)
4519 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4520 if (acfg->stats.abscount)
4521 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4522 if (acfg->stats.wrappercount)
4523 printf ("%d methods contain wrapper references (%d%%)\n", acfg->stats.wrappercount, acfg->stats.mcount ? (acfg->stats.wrappercount * 100) / acfg->stats.mcount : 100);
4524 if (acfg->stats.lmfcount)
4525 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4526 if (acfg->stats.ocount)
4527 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4528 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);
4529 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4531 printf ("GOT slot distribution:\n");
4532 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4533 if (acfg->stats.got_slot_types [i])
4534 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4546 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)