2 * aot.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
11 /* Remaining AOT-only work:
12 * - reduce the length of the wrapper names.
13 * - aot IMT tables, so we don't have two kinds of aot code.
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
23 * - every shared method has a MonoGenericJitInfo structure which is only really
24 * used for handling catch clauses with open types, not a very common use case.
28 #include <sys/types.h>
38 #ifndef PLATFORM_WIN32
49 #include <limits.h> /* for PAGESIZE */
54 #include <mono/metadata/tabledefs.h>
55 #include <mono/metadata/class.h>
56 #include <mono/metadata/object.h>
57 #include <mono/metadata/tokentype.h>
58 #include <mono/metadata/appdomain.h>
59 #include <mono/metadata/debug-helpers.h>
60 #include <mono/metadata/assembly.h>
61 #include <mono/metadata/metadata-internals.h>
62 #include <mono/metadata/marshal.h>
63 #include <mono/metadata/gc-internal.h>
64 #include <mono/metadata/method-builder.h>
65 #include <mono/metadata/monitor.h>
66 #include <mono/utils/mono-logger.h>
67 #include "mono/utils/mono-compiler.h"
75 #define TV_DECLARE(name)
76 #define TV_GETTIME(tv)
77 #define TV_ELAPSED(start, end) 0
79 #define TV_DECLARE(name) struct timeval name
80 #define TV_GETTIME(tv) gettimeofday (&(tv), NULL)
81 #define TV_ELAPSED(start,end) (int)((((end).tv_sec - (start).tv_sec) * 1000000) + end.tv_usec - start.tv_usec)
85 #define SHARED_EXT ".dll"
86 #elif defined(__ppc__) && defined(__MACH__)
87 #define SHARED_EXT ".dylib"
89 #define SHARED_EXT ".so"
92 #if defined(sparc) || defined(__ppc__) || defined(__powerpc__) || defined(__MACH__)
93 #define AS_STRING_DIRECTIVE ".asciz"
96 #define AS_STRING_DIRECTIVE ".string"
101 // .byte generates 1 byte per expression.
102 // .short generates 2 bytes per expression.
103 // .long generates 4 bytes per expression.
104 // .quad generates 8 bytes per expression.
106 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
107 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
109 typedef struct MonoAotOptions {
112 gboolean write_symbols;
113 gboolean metadata_only;
114 gboolean bind_to_runtime_version;
117 gboolean static_link;
121 typedef struct MonoAotStats {
122 int ccount, mcount, lmfcount, abscount, wrappercount, gcount, ocount, genericcount;
123 int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
124 int methods_without_got_slots, direct_calls, all_calls;
126 int got_slot_types [MONO_PATCH_INFO_NONE];
127 int jit_time, gen_time, link_time;
130 #if defined(__x86_64__) && defined(HAVE_ELF_H)
131 //#define USE_ELF_WRITER 1
132 #define USE_ELF_RELA 1
135 //#define USE_ELF_WRITER 1
137 #if defined(USE_ELF_WRITER)
138 #define USE_BIN_WRITER 1
141 #ifdef USE_BIN_WRITER
143 typedef struct _BinSymbol BinSymbol;
144 typedef struct _BinReloc BinReloc;
145 typedef struct _BinSection BinSection;
159 typedef struct MonoAotCompile {
162 GHashTable *method_indexes;
165 GHashTable *patch_to_plt_offset;
166 GHashTable *plt_offset_to_patch;
167 GHashTable *patch_to_shared_got_offset;
168 GPtrArray *shared_patches;
169 GHashTable *image_hash;
170 GHashTable *method_to_cfg;
171 GHashTable *token_info_hash;
172 GPtrArray *extra_methods;
173 GPtrArray *image_table;
176 /* Number of trampolines emitted into the AOT file */
177 guint32 num_aot_trampolines;
178 guint32 got_offset, plt_offset;
179 /* Number of GOT entries reserved for trampolines */
180 guint32 num_trampoline_got_entries;
181 MonoAotOptions aot_opts;
184 MonoMemPool *mempool;
187 char *static_linking_symbol;
188 #ifdef USE_BIN_WRITER
190 BinSection *sections;
191 BinSection *cur_section;
192 BinReloc *relocations;
198 int mode; /* emit mode */
199 int col_count; /* bytes emitted per .byte line */
203 #ifdef HAVE_ARRAY_ELEM_INIT
204 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
205 #define MSGSTRFIELD1(line) str##line
206 static const struct msgstr_t {
207 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
208 #include "patch-info.h"
211 #define PATCH_INFO(a,b) b,
212 #include "patch-info.h"
215 static const gint16 opidx [] = {
216 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
217 #include "patch-info.h"
222 get_patch_name (int info)
224 return (const char*)&opstr + opidx [info];
228 #define PATCH_INFO(a,b) b,
229 static const char* const
230 patch_types [MONO_PATCH_INFO_NUM + 1] = {
231 #include "patch-info.h"
236 get_patch_name (int info)
238 return patch_types [info];
244 emit_global (MonoAotCompile *acfg, const char *name, gboolean func);
247 is_got_patch (MonoJumpInfoType patch_type)
252 static G_GNUC_UNUSED int
253 ilog2(register int value)
256 while (value & ~0xf) count += 4, value >>= 4;
257 while (value) count++, value >>= 1;
261 #ifdef USE_BIN_WRITER
263 typedef struct _BinLabel BinLabel;
274 BinSection *val2_section;
286 gboolean is_function;
304 emit_start (MonoAotCompile *acfg)
306 acfg->labels = g_hash_table_new (g_str_hash, g_str_equal);
310 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
314 if (acfg->cur_section && acfg->cur_section->subsection == subsection_index
315 && strcmp (acfg->cur_section->name, section_name) == 0)
317 for (section = acfg->sections; section; section = section->next) {
318 if (section->subsection == subsection_index && strcmp (section->name, section_name) == 0) {
319 acfg->cur_section = section;
324 section = g_new0 (BinSection, 1);
325 section->name = g_strdup (section_name);
326 section->subsection = subsection_index;
327 section->next = acfg->sections;
328 acfg->sections = section;
329 acfg->cur_section = section;
334 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
336 BinSymbol *symbol = g_new0 (BinSymbol, 1);
337 symbol->name = g_strdup (name);
338 symbol->is_function = func;
339 symbol->is_global = TRUE;
340 symbol->section = acfg->cur_section;
341 /* FIXME: we align after this call... */
342 symbol->offset = symbol->section->cur_offset;
343 symbol->next = acfg->symbols;
344 acfg->symbols = symbol;
348 emit_label (MonoAotCompile *acfg, const char *name)
350 BinLabel *label = g_new0 (BinLabel, 1);
351 label->name = g_strdup (name);
352 label->section = acfg->cur_section;
353 label->offset = acfg->cur_section->cur_offset;
354 g_hash_table_insert (acfg->labels, label->name, label);
358 emit_ensure_buffer (BinSection *section, int size)
360 int new_offset = section->cur_offset + size;
361 if (new_offset >= section->data_len) {
362 int new_size = section->data_len? section->data_len * 2: 256;
364 while (new_size <= new_offset)
366 data = g_malloc0 (new_size);
367 memcpy (data, section->data, section->data_len);
368 g_free (section->data);
369 section->data = data;
370 section->data_len = new_size;
375 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
377 emit_ensure_buffer (acfg->cur_section, size);
378 memcpy (acfg->cur_section->data + acfg->cur_section->cur_offset, buf, size);
379 acfg->cur_section->cur_offset += size;
383 emit_string (MonoAotCompile *acfg, const char *value)
385 int size = strlen (value) + 1;
386 emit_bytes (acfg, (const guint8*)value, size);
390 emit_line (MonoAotCompile *acfg)
392 /* Nothing to do in binary writer */
396 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
398 emit_section_change (acfg, ".text", 1);
399 emit_global (acfg, name, FALSE);
400 emit_label (acfg, name);
401 emit_string (acfg, value);
405 emit_alignment (MonoAotCompile *acfg, int size)
407 int offset = acfg->cur_section->cur_offset;
409 offset += (size - 1);
410 offset &= ~(size - 1);
411 add = offset - acfg->cur_section->cur_offset;
413 emit_ensure_buffer (acfg->cur_section, add);
414 acfg->cur_section->cur_offset += add;
419 emit_pointer (MonoAotCompile *acfg, const char *target)
425 g_assert_not_reached ();
426 emit_alignment (acfg, sizeof (gpointer));
427 reloc = g_new0 (BinReloc, 1);
428 reloc->val1 = g_strdup (target);
429 reloc->section = acfg->cur_section;
430 reloc->section_offset = acfg->cur_section->cur_offset;
431 reloc->next = acfg->relocations;
432 acfg->relocations = reloc;
433 if (strcmp (reloc->section->name, ".data") == 0) {
435 g_print ("reloc: %s at %d\n", target, acfg->cur_section->cur_offset);
437 acfg->cur_section->cur_offset += sizeof (gpointer);
441 emit_int16 (MonoAotCompile *acfg, int value)
444 emit_ensure_buffer (acfg->cur_section, 2);
445 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
446 acfg->cur_section->cur_offset += 2;
447 /* FIXME: little endian */
449 data [1] = value >> 8;
453 emit_int32 (MonoAotCompile *acfg, int value)
456 emit_ensure_buffer (acfg->cur_section, 4);
457 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
458 acfg->cur_section->cur_offset += 4;
459 /* FIXME: little endian */
461 data [1] = value >> 8;
462 data [2] = value >> 16;
463 data [3] = value >> 24;
467 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
470 reloc = g_new0 (BinReloc, 1);
471 reloc->val1 = g_strdup (end);
472 if (strcmp (start, ".") == 0) {
473 reloc->val2_section = acfg->cur_section;
474 reloc->val2_offset = acfg->cur_section->cur_offset;
476 reloc->val2 = g_strdup (start);
478 reloc->offset = offset;
479 reloc->section = acfg->cur_section;
480 reloc->section_offset = acfg->cur_section->cur_offset;
481 reloc->next = acfg->relocations;
482 acfg->relocations = reloc;
483 acfg->cur_section->cur_offset += 4;
484 /*if (strcmp (reloc->section->name, ".data") == 0) {
486 g_print ("reloc: %s - %s + %d at %d\n", end, start, offset, acfg->cur_section->cur_offset - 4);
491 emit_zero_bytes (MonoAotCompile *acfg, int num)
493 emit_ensure_buffer (acfg->cur_section, num);
494 acfg->cur_section->cur_offset += num;
497 #ifdef USE_ELF_WRITER
517 #if SIZEOF_VOID_P == 4
519 typedef Elf32_Ehdr ElfHeader;
520 typedef Elf32_Shdr ElfSectHeader;
521 typedef Elf32_Phdr ElfProgHeader;
522 typedef Elf32_Sym ElfSymbol;
523 typedef Elf32_Rel ElfReloc;
524 typedef Elf32_Rela ElfRelocA;
525 typedef Elf32_Dyn ElfDynamic;
529 typedef Elf64_Ehdr ElfHeader;
530 typedef Elf64_Shdr ElfSectHeader;
531 typedef Elf64_Phdr ElfProgHeader;
532 typedef Elf64_Sym ElfSymbol;
533 typedef Elf64_Rel ElfReloc;
534 typedef Elf64_Rela ElfRelocA;
535 typedef Elf64_Dyn ElfDynamic;
547 static SectInfo section_info [] = {
549 {".hash", SHT_HASH, 4, 2, SIZEOF_VOID_P},
550 {".dynsym", SHT_DYNSYM, sizeof (ElfSymbol), 2, SIZEOF_VOID_P},
551 {".dynstr", SHT_STRTAB, 0, 2, 1},
552 {".rel.dyn", SHT_REL, sizeof (ElfReloc), 2, SIZEOF_VOID_P},
553 {".rela.dyn", SHT_RELA, sizeof (ElfRelocA), 2, SIZEOF_VOID_P},
554 {".text", SHT_PROGBITS, 0, 6, 4096},
555 {".dynamic", SHT_DYNAMIC, sizeof (ElfDynamic), 3, SIZEOF_VOID_P},
556 {".got.plt", SHT_PROGBITS, SIZEOF_VOID_P, 3, SIZEOF_VOID_P},
557 {".data", SHT_PROGBITS, 0, 3, 8},
558 {".bss", SHT_NOBITS, 0, 3, 8},
559 {".shstrtab", SHT_STRTAB, 0, 0, 1},
560 {".symtab", SHT_SYMTAB, sizeof (ElfSymbol), 0, SIZEOF_VOID_P},
561 {".strtab", SHT_STRTAB, 0, 0, 1}
570 str_table_add (ElfStrTable *table, const char* value)
574 table->data = g_string_new_len ("", 1);
575 table->hash = g_hash_table_new (g_str_hash, g_str_equal);
577 idx = GPOINTER_TO_UINT (g_hash_table_lookup (table->hash, value));
580 idx = table->data->len;
581 g_string_append (table->data, value);
582 g_string_append_c (table->data, 0);
583 g_hash_table_insert (table->hash, (void*)value, GUINT_TO_POINTER (idx));
588 append_subsection (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection *sect, BinSection *add)
590 int offset = sect->cur_offset;
591 /*offset += (sheaders [sect->shidx].sh_addralign - 1);
592 offset &= ~(sheaders [sect->shidx].sh_addralign - 1);*/
595 emit_ensure_buffer (sect, offset);
596 g_print ("section %s aligned to %d from %d\n", sect->name, offset, sect->cur_offset);
597 sect->cur_offset = offset;
599 emit_ensure_buffer (sect, add->cur_offset);
600 memcpy (sect->data + sect->cur_offset, add->data, add->cur_offset);
602 sect->cur_offset += add->cur_offset;
603 add->cur_offset = offset; /* it becomes the offset in the parent section */
604 g_print ("subsection %d of %s added at offset %d (align: %d)\n", add->subsection, sect->name, add->cur_offset, (int)sheaders [sect->shidx].sh_addralign);
609 /* merge the subsections */
611 collect_sections (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection **out, int num)
613 int i, j, maxs, num_sections;
618 for (sect = acfg->sections; sect; sect = sect->next) {
619 if (sect->subsection == 0) {
620 out [num_sections++] = sect;
621 g_assert (num_sections < num);
622 if (strcmp (sect->name, ".text") == 0) {
623 sect->shidx = SECT_TEXT;
624 } else if (strcmp (sect->name, ".data") == 0) {
625 sect->shidx = SECT_DATA;
626 } else if (strcmp (sect->name, ".bss") == 0) {
627 sect->shidx = SECT_BSS;
630 maxs = MAX (maxs, sect->subsection);
632 for (i = 0; i < num_sections; i++) {
633 for (j = 1; j <= maxs; ++j) {
634 for (sect = acfg->sections; sect; sect = sect->next) {
635 if (sect->subsection == j && strcmp (out [i]->name, sect->name) == 0) {
636 append_subsection (acfg, sheaders, out [i], sect);
645 elf_hash (const unsigned char *name)
647 unsigned long h = 0, g;
649 h = (h << 4) + *name++;
650 if ((g = h & 0xf0000000))
657 #define NUM_BUCKETS 17
660 build_hash (MonoAotCompile *acfg, int num_sections, ElfStrTable *dynstr)
663 int num_symbols = 1 + num_sections + 3;
666 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
667 if (!symbol->is_global)
670 str_table_add (dynstr, symbol->name);
671 /*g_print ("adding sym: %s\n", symbol->name);*/
673 str_table_add (dynstr, "__bss_start");
674 str_table_add (dynstr, "_edata");
675 str_table_add (dynstr, "_end");
677 data = g_new0 (int, num_symbols + 2 + NUM_BUCKETS);
678 data [0] = NUM_BUCKETS;
679 data [1] = num_symbols;
685 get_label_addr (MonoAotCompile *acfg, const char *name)
692 lab = g_hash_table_lookup (acfg->labels, name);
693 section = lab->section;
694 offset = lab->offset;
695 if (section->parent) {
696 value = section->parent->virt_offset + section->cur_offset + offset;
698 value = section->virt_offset + offset;
704 collect_syms (MonoAotCompile *acfg, int *hash, ElfStrTable *strtab, ElfSectHeader *sheaders, int *num_syms)
715 symbols = g_new0 (ElfSymbol, hash [1]);
717 symbols = g_new0 (ElfSymbol, *num_syms + SECT_NUM + 10); /* FIXME */
719 /* the first symbol is undef, all zeroes */
723 for (j = 1; j < SECT_NUM; ++j) {
724 symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
725 symbols [i].st_shndx = j;
726 symbols [i].st_value = sheaders [j].sh_addr;
730 for (section = acfg->sections; section; section = section->next) {
733 symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
734 if (strcmp (section->name, ".text") == 0) {
735 symbols [i].st_shndx = SECT_TEXT;
736 section->shidx = SECT_TEXT;
737 section->file_offset = 4096;
738 symbols [i].st_value = section->virt_offset;
739 } else if (strcmp (section->name, ".data") == 0) {
740 symbols [i].st_shndx = SECT_DATA;
741 section->shidx = SECT_DATA;
742 section->file_offset = 4096 + 28; /* FIXME */
743 symbols [i].st_value = section->virt_offset;
744 } else if (strcmp (section->name, ".bss") == 0) {
745 symbols [i].st_shndx = SECT_BSS;
746 section->shidx = SECT_BSS;
747 section->file_offset = 4096 + 28 + 8; /* FIXME */
748 symbols [i].st_value = section->virt_offset;
753 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
756 if (!symbol->is_global)
758 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, symbol->is_function? STT_FUNC : STT_OBJECT);
759 symbols [i].st_name = str_table_add (strtab, symbol->name);
760 /*g_print ("sym name %s tabled to %d\n", symbol->name, symbols [i].st_name);*/
761 section = symbol->section;
762 symbols [i].st_shndx = section->parent? section->parent->shidx: section->shidx;
763 lab = g_hash_table_lookup (acfg->labels, symbol->name);
764 offset = lab->offset;
765 if (section->parent) {
766 symbols [i].st_value = section->parent->virt_offset + section->cur_offset + offset;
768 symbols [i].st_value = section->virt_offset + offset;
772 /* add special symbols */
773 symbols [i].st_name = str_table_add (strtab, "__bss_start");
774 symbols [i].st_shndx = 0xfff1;
775 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
777 symbols [i].st_name = str_table_add (strtab, "_edata");
778 symbols [i].st_shndx = 0xfff1;
779 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
781 symbols [i].st_name = str_table_add (strtab, "_end");
782 symbols [i].st_shndx = 0xfff1;
783 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
789 /* add to hash table */
792 chain = hash + 2 + hash [0];
793 for (i = 0; i < hash [1]; ++i) {
795 /*g_print ("checking %d '%s' (sym %d)\n", symbols [i].st_name, strtab->data->str + symbols [i].st_name, i);*/
796 if (!symbols [i].st_name)
798 hashc = elf_hash ((guint8*)strtab->data->str + symbols [i].st_name);
799 slot = hashc % hash [0];
800 /*g_print ("hashing '%s' at slot %d (sym %d)\n", strtab->data->str + symbols [i].st_name, slot, i);*/
802 chain [i] = bucket [slot];
813 reloc_symbols (MonoAotCompile *acfg, ElfSymbol *symbols, ElfSectHeader *sheaders, ElfStrTable *strtab, gboolean dynamic)
821 for (section = acfg->sections; section; section = section->next) {
824 symbols [i].st_value = sheaders [section->shidx].sh_addr;
828 for (i = 1; i < SECT_NUM; ++i) {
829 symbols [i].st_value = sheaders [i].sh_addr;
832 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
835 if (dynamic && !symbol->is_global)
837 section = symbol->section;
838 lab = g_hash_table_lookup (acfg->labels, symbol->name);
839 offset = lab->offset;
840 if (section->parent) {
841 symbols [i].st_value = sheaders [section->parent->shidx].sh_addr + section->cur_offset + offset;
843 symbols [i].st_value = sheaders [section->shidx].sh_addr + offset;
848 symbols [i].st_value = sheaders [SECT_BSS].sh_addr;
851 symbols [i].st_value = sheaders [SECT_DATA].sh_addr + sheaders [SECT_DATA].sh_size;
854 symbols [i].st_value = sheaders [SECT_BSS].sh_addr + sheaders [SECT_BSS].sh_size;
859 resolve_reloc (MonoAotCompile *acfg, BinReloc *reloc, guint8 **out_data, gsize *out_vaddr, gsize *out_start_val, gsize *out_end_val)
862 gsize end_val, start_val;
865 end_val = get_label_addr (acfg, reloc->val1);
867 start_val = get_label_addr (acfg, reloc->val2);
868 } else if (reloc->val2_section) {
869 start_val = reloc->val2_offset;
870 if (reloc->val2_section->parent)
871 start_val += reloc->val2_section->parent->virt_offset + reloc->val2_section->cur_offset;
873 start_val += reloc->val2_section->virt_offset;
877 end_val = end_val - start_val + reloc->offset;
878 if (reloc->section->parent) {
879 data = reloc->section->parent->data;
880 data += reloc->section->cur_offset;
881 data += reloc->section_offset;
882 vaddr = reloc->section->parent->virt_offset;
883 vaddr += reloc->section->cur_offset;
884 vaddr += reloc->section_offset;
886 data = reloc->section->data;
887 data += reloc->section_offset;
888 vaddr = reloc->section->virt_offset;
889 vaddr += reloc->section_offset;
892 *out_start_val = start_val;
893 *out_end_val = end_val;
901 resolve_relocations (MonoAotCompile *acfg)
905 gsize end_val, start_val;
910 rr = g_new0 (ElfRelocA, acfg->num_relocs);
913 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
914 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
915 /* FIXME: little endian */
917 data [1] = end_val >> 8;
918 data [2] = end_val >> 16;
919 data [3] = end_val >> 24;
920 if (start_val == 0) {
921 rr [i].r_offset = vaddr;
922 rr [i].r_info = R_X86_64_RELATIVE;
923 rr [i].r_addend = end_val;
925 g_assert (i <= acfg->num_relocs);
931 #else /* USE_ELF_RELA */
934 resolve_relocations (MonoAotCompile *acfg)
938 gsize end_val, start_val;
943 rr = g_new0 (ElfReloc, acfg->num_relocs);
946 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
947 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
948 /* FIXME: little endian */
950 data [1] = end_val >> 8;
951 data [2] = end_val >> 16;
952 data [3] = end_val >> 24;
953 if (start_val == 0) {
954 rr [i].r_offset = vaddr;
955 rr [i].r_info = 8; /* FIXME: 386_RELATIVE */
957 g_assert (i <= acfg->num_relocs);
963 #endif /* USE_ELF_RELA */
966 emit_writeout (MonoAotCompile *acfg)
968 char *outfile_name, *tmp_outfile_name;
971 ElfProgHeader progh [3];
972 ElfSectHeader secth [SECT_NUM];
978 ElfStrTable str_table = {NULL, NULL};
979 ElfStrTable sh_str_table = {NULL, NULL};
980 ElfStrTable dyn_str_table = {NULL, NULL};
981 BinSection* sections [6];
982 BinSection *text_section = NULL, *data_section = NULL, *bss_section = NULL;
985 ElfDynamic dynamic [14];
987 int i, num_sections, file_offset, virt_offset, size, num_symtab;
990 g_assert (!acfg->aot_opts.asm_only);
992 if (acfg->aot_opts.outfile)
993 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
995 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
997 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
999 unlink (tmp_outfile_name);
1000 file = fopen (tmp_outfile_name, "w");
1003 /* Section headers */
1004 memset (§h, 0, sizeof (secth));
1005 memset (&dynamic, 0, sizeof (dynamic));
1006 memset (&header, 0, sizeof (header));
1008 for (i = 1; i < SECT_NUM; ++i) {
1009 secth [i].sh_name = str_table_add (&sh_str_table, section_info [i].name);
1010 secth [i].sh_type = section_info [i].type;
1011 secth [i].sh_addralign = section_info [i].align;
1012 secth [i].sh_flags = section_info [i].flags;
1013 secth [i].sh_entsize = section_info [i].esize;
1015 secth [SECT_DYNSYM].sh_info = SIZEOF_VOID_P == 4 ? 4 : 2;
1016 secth [SECT_SYMTAB].sh_info = SIZEOF_VOID_P == 4 ? 20 : 17;
1017 secth [SECT_HASH].sh_link = SECT_DYNSYM;
1018 secth [SECT_DYNSYM].sh_link = SECT_DYNSTR;
1019 secth [SECT_REL_DYN].sh_link = SECT_DYNSYM;
1020 secth [SECT_RELA_DYN].sh_link = SECT_DYNSYM;
1021 secth [SECT_DYNAMIC].sh_link = SECT_DYNSTR;
1022 secth [SECT_SYMTAB].sh_link = SECT_STRTAB;
1024 num_sections = collect_sections (acfg, secth, sections, 6);
1025 hash = build_hash (acfg, num_sections, &dyn_str_table);
1026 num_symtab = hash [1]; /* FIXME */
1027 g_print ("num_sections: %d\n", num_sections);
1028 g_print ("dynsym: %d, dynstr size: %d\n", hash [1], (int)dyn_str_table.data->len);
1029 for (i = 0; i < num_sections; ++i) {
1030 g_print ("section %s, size: %d, %x\n", sections [i]->name, sections [i]->cur_offset, sections [i]->cur_offset);
1033 /* at this point we know where in the file the first segment sections go */
1034 dynsym = collect_syms (acfg, hash, &dyn_str_table, NULL, NULL);
1035 num_local_syms = hash [1];
1036 symtab = collect_syms (acfg, NULL, &str_table, secth, &num_local_syms);
1038 for (i = 0; i < num_sections; ++i) {
1039 if (sections [i]->shidx == SECT_TEXT) {
1040 text_section = sections [i];
1041 } else if (sections [i]->shidx == SECT_DATA) {
1042 data_section = sections [i];
1043 } else if (sections [i]->shidx == SECT_BSS) {
1044 bss_section = sections [i];
1048 file_offset = virt_offset = sizeof (header) + sizeof (progh);
1049 secth [SECT_HASH].sh_addr = secth [SECT_HASH].sh_offset = file_offset;
1050 size = sizeof (int) * (2 + hash [0] + hash [1]);
1051 virt_offset = (file_offset += size);
1052 secth [SECT_HASH].sh_size = size;
1053 secth [SECT_DYNSYM].sh_addr = secth [SECT_DYNSYM].sh_offset = file_offset;
1054 size = sizeof (ElfSymbol) * hash [1];
1055 virt_offset = (file_offset += size);
1056 secth [SECT_DYNSYM].sh_size = size;
1057 secth [SECT_DYNSTR].sh_addr = secth [SECT_DYNSTR].sh_offset = file_offset;
1058 size = dyn_str_table.data->len;
1059 virt_offset = (file_offset += size);
1060 secth [SECT_DYNSTR].sh_size = size;
1062 file_offset &= ~(4-1);
1063 secth [SECT_REL_DYN].sh_addr = secth [SECT_REL_DYN].sh_offset = file_offset;
1064 #ifndef USE_ELF_RELA
1065 size = sizeof (ElfReloc) * acfg->num_relocs;
1069 virt_offset = (file_offset += size);
1070 secth [SECT_REL_DYN].sh_size = size;
1071 secth [SECT_RELA_DYN].sh_addr = secth [SECT_RELA_DYN].sh_offset = file_offset;
1073 size = sizeof (ElfRelocA) * acfg->num_relocs;
1077 virt_offset = (file_offset += size);
1078 secth [SECT_RELA_DYN].sh_size = size;
1079 file_offset += 4096-1;
1080 file_offset &= ~(4096-1);
1081 virt_offset = file_offset;
1082 secth [SECT_TEXT].sh_addr = secth [SECT_TEXT].sh_offset = file_offset;
1083 size = text_section->cur_offset;
1084 secth [SECT_TEXT].sh_size = size;
1085 file_offset += size;
1087 file_offset &= ~(4-1);
1088 virt_offset = file_offset;
1089 /* .dynamic, .got.plt, .data, .bss here */
1090 /* Have to increase the virt offset since these go to a separate segment */
1091 virt_offset += PAGESIZE;
1092 secth [SECT_DYNAMIC].sh_addr = virt_offset;
1093 secth [SECT_DYNAMIC].sh_offset = file_offset;
1094 size = sizeof (dynamic);
1095 secth [SECT_DYNAMIC].sh_size = size;
1098 file_offset += size;
1099 virt_offset += size;
1100 secth [SECT_GOT_PLT].sh_addr = virt_offset;
1101 secth [SECT_GOT_PLT].sh_offset = file_offset;
1103 secth [SECT_GOT_PLT].sh_size = size;
1106 file_offset += size;
1107 virt_offset += size;
1108 secth [SECT_DATA].sh_addr = virt_offset;
1109 secth [SECT_DATA].sh_offset = file_offset;
1110 size = data_section->cur_offset;
1111 secth [SECT_DATA].sh_size = size;
1114 file_offset += size;
1115 virt_offset += size;
1116 secth [SECT_BSS].sh_addr = virt_offset;
1117 secth [SECT_BSS].sh_offset = file_offset;
1118 size = bss_section->cur_offset;
1119 secth [SECT_BSS].sh_size = size;
1121 /* virtual doesn't matter anymore */
1122 secth [SECT_SHSTRTAB].sh_offset = file_offset;
1123 size = sh_str_table.data->len;
1124 secth [SECT_SHSTRTAB].sh_size = size;
1125 size += SIZEOF_VOID_P-1;
1126 size &= ~(SIZEOF_VOID_P-1);
1127 file_offset += size;
1128 secth [SECT_SYMTAB].sh_offset = file_offset;
1129 size = sizeof (ElfSymbol) * num_local_syms;
1130 secth [SECT_SYMTAB].sh_size = size;
1131 file_offset += size;
1132 secth [SECT_STRTAB].sh_offset = file_offset;
1133 size = str_table.data->len;
1134 secth [SECT_STRTAB].sh_size = size;
1135 file_offset += size;
1137 file_offset &= ~(4-1);
1139 text_section->file_offset = secth [SECT_TEXT].sh_offset;
1140 text_section->virt_offset = secth [SECT_TEXT].sh_addr;
1141 data_section->file_offset = secth [SECT_DATA].sh_offset;
1142 data_section->virt_offset = secth [SECT_DATA].sh_addr;
1143 bss_section->file_offset = secth [SECT_BSS].sh_offset;
1144 bss_section->virt_offset = secth [SECT_BSS].sh_addr;
1146 header.e_ident [EI_MAG0] = ELFMAG0;
1147 header.e_ident [EI_MAG1] = ELFMAG1;
1148 header.e_ident [EI_MAG2] = ELFMAG2;
1149 header.e_ident [EI_MAG3] = ELFMAG3;
1150 header.e_ident [EI_CLASS] = SIZEOF_VOID_P == 4 ? ELFCLASS32 : ELFCLASS64;
1151 header.e_ident [EI_DATA] = ELFDATA2LSB;
1152 header.e_ident [EI_VERSION] = EV_CURRENT;
1153 header.e_ident [EI_OSABI] = ELFOSABI_NONE;
1154 header.e_ident [EI_ABIVERSION] = 0;
1155 for (i = EI_PAD; i < EI_NIDENT; ++i)
1156 header.e_ident [i] = 0;
1158 header.e_type = ET_DYN;
1159 #if defined(__i386__)
1160 header.e_machine = EM_386;
1161 #elif defined(__x86_64__)
1162 header.e_machine = EM_X86_64;
1164 g_assert_not_reached ();
1166 header.e_version = 1;
1168 header.e_phoff = sizeof (header);
1169 header.e_ehsize = sizeof (header);
1170 header.e_phentsize = sizeof (ElfProgHeader);
1172 header.e_entry = secth [SECT_TEXT].sh_addr;
1173 header.e_shstrndx = SECT_SHSTRTAB;
1174 header.e_shentsize = sizeof (ElfSectHeader);
1175 header.e_shnum = SECT_NUM;
1176 header.e_shoff = file_offset;
1180 dynamic [i].d_tag = DT_HASH;
1181 dynamic [i].d_un.d_val = secth [SECT_HASH].sh_offset;
1183 dynamic [i].d_tag = DT_STRTAB;
1184 dynamic [i].d_un.d_val = secth [SECT_DYNSTR].sh_offset;
1186 dynamic [i].d_tag = DT_SYMTAB;
1187 dynamic [i].d_un.d_val = secth [SECT_DYNSYM].sh_offset;
1189 dynamic [i].d_tag = DT_STRSZ;
1190 dynamic [i].d_un.d_val = dyn_str_table.data->len;
1192 dynamic [i].d_tag = DT_SYMENT;
1193 dynamic [i].d_un.d_val = sizeof (ElfSymbol);
1196 dynamic [i].d_tag = DT_RELA;
1197 dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_offset;
1199 dynamic [i].d_tag = DT_RELASZ;
1200 dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_size;
1202 dynamic [i].d_tag = DT_RELAENT;
1203 dynamic [i].d_un.d_val = sizeof (ElfRelocA);
1206 dynamic [i].d_tag = DT_REL;
1207 dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_offset;
1209 dynamic [i].d_tag = DT_RELSZ;
1210 dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_size;
1212 dynamic [i].d_tag = DT_RELENT;
1213 dynamic [i].d_un.d_val = sizeof (ElfReloc);
1216 dynamic [i].d_tag = DT_RELCOUNT;
1217 dynamic [i].d_un.d_val = acfg->num_relocs;
1220 /* Program header */
1221 memset (&progh, 0, sizeof (progh));
1222 progh [0].p_type = PT_LOAD;
1223 progh [0].p_filesz = progh [0].p_memsz = secth [SECT_DYNAMIC].sh_offset;
1224 progh [0].p_align = 4096;
1225 progh [0].p_flags = 5;
1227 progh [1].p_type = PT_LOAD;
1228 progh [1].p_offset = secth [SECT_DYNAMIC].sh_offset;
1229 progh [1].p_vaddr = progh [1].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1230 progh [1].p_filesz = secth [SECT_BSS].sh_offset - secth [SECT_DYNAMIC].sh_offset;
1231 progh [1].p_memsz = secth [SECT_BSS].sh_addr + secth [SECT_BSS].sh_size - secth [SECT_DYNAMIC].sh_addr;
1232 progh [1].p_align = 4096;
1233 progh [1].p_flags = 6;
1235 progh [2].p_type = PT_DYNAMIC;
1236 progh [2].p_offset = secth [SECT_DYNAMIC].sh_offset;
1237 progh [2].p_vaddr = progh [2].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1238 progh [2].p_filesz = progh [2].p_memsz = secth [SECT_DYNAMIC].sh_size;
1239 progh [2].p_align = SIZEOF_VOID_P;
1240 progh [2].p_flags = 6;
1242 reloc_symbols (acfg, dynsym, secth, &dyn_str_table, TRUE);
1243 reloc_symbols (acfg, symtab, secth, &str_table, FALSE);
1244 relocs = resolve_relocations (acfg);
1246 fwrite (&header, sizeof (header), 1, file);
1247 fwrite (&progh, sizeof (progh), 1, file);
1248 fwrite (hash, sizeof (int) * (hash [0] + hash [1] + 2), 1, file);
1249 fwrite (dynsym, sizeof (ElfSymbol) * hash [1], 1, file);
1250 fwrite (dyn_str_table.data->str, dyn_str_table.data->len, 1, file);
1252 fseek (file, secth [SECT_REL_DYN].sh_offset, SEEK_SET);
1253 fwrite (relocs, sizeof (ElfReloc), acfg->num_relocs, file);
1256 fseek (file, secth [SECT_RELA_DYN].sh_offset, SEEK_SET);
1257 fwrite (relocs, secth [SECT_RELA_DYN].sh_size, 1, file);
1259 fseek (file, secth [SECT_TEXT].sh_offset, SEEK_SET);
1260 /* write .text, .data, .bss sections */
1261 fwrite (text_section->data, text_section->cur_offset, 1, file);
1264 fwrite (dynamic, sizeof (dynamic), 1, file);
1266 size = secth [SECT_DYNAMIC].sh_addr;
1267 fwrite (&size, sizeof (size), 1, file);
1268 fseek (file, secth [SECT_DATA].sh_offset, SEEK_SET);
1269 fwrite (data_section->data, data_section->cur_offset, 1, file);
1271 fseek (file, secth [SECT_SHSTRTAB].sh_offset, SEEK_SET);
1272 fwrite (sh_str_table.data->str, sh_str_table.data->len, 1, file);
1273 fseek (file, secth [SECT_SYMTAB].sh_offset, SEEK_SET);
1274 fwrite (symtab, sizeof (ElfSymbol) * num_local_syms, 1, file);
1275 fseek (file, secth [SECT_STRTAB].sh_offset, SEEK_SET);
1276 fwrite (str_table.data->str, str_table.data->len, 1, file);
1277 /*g_print ("file_offset %d vs %d\n", file_offset, ftell (file));*/
1278 /*g_assert (file_offset >= ftell (file));*/
1279 fseek (file, file_offset, SEEK_SET);
1280 fwrite (§h, sizeof (secth), 1, file);
1282 rename (tmp_outfile_name, outfile_name);
1284 g_free (tmp_outfile_name);
1285 g_free (outfile_name);
1290 #endif /* USE_ELF_WRITER */
1295 emit_start (MonoAotCompile *acfg)
1297 if (acfg->aot_opts.asm_only) {
1298 if (acfg->aot_opts.outfile)
1299 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1301 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
1302 acfg->fp = fopen (acfg->tmpfname, "w+");
1304 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
1305 acfg->fp = fdopen (i, "w+");
1307 g_assert (acfg->fp);
1311 emit_unset_mode (MonoAotCompile *acfg)
1313 if (acfg->mode == EMIT_NONE)
1315 fprintf (acfg->fp, "\n");
1316 acfg->mode = EMIT_NONE;
1320 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
1322 emit_unset_mode (acfg);
1323 #if defined(PLATFORM_WIN32)
1324 fprintf (acfg->fp, ".section %s\n", section_name);
1325 #elif defined(__MACH__)
1326 if (strcmp(section_name, ".bss") == 0)
1327 fprintf (acfg->fp, "%s\n", ".data");
1329 fprintf (acfg->fp, "%s\n", section_name);
1330 #elif defined(sparc) || defined(__arm__)
1331 /* For solaris as, GNU as should accept the same */
1332 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1334 fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1339 emit_symbol_type (MonoAotCompile *acfg, const char *name, gboolean func)
1348 emit_unset_mode (acfg);
1349 #if defined(__MACH__)
1351 #elif defined(sparc) || defined(__arm__)
1352 fprintf (acfg->fp, "\t.type %s,#%s\n", name, stype);
1353 #elif defined(PLATFORM_WIN32)
1355 #elif defined(__x86_64__) || defined(__i386__)
1356 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1358 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1363 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
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, "\t.globl _%s\n", name);
1370 fprintf (acfg->fp, "\t.globl %s\n", name);
1373 emit_symbol_type (acfg, name, func);
1377 emit_label (MonoAotCompile *acfg, const char *name)
1379 emit_unset_mode (acfg);
1380 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1381 // mach-o always uses a '_' prefix.
1382 fprintf (acfg->fp, "_%s:\n", name);
1384 fprintf (acfg->fp, "%s:\n", name);
1387 #if defined(PLATFORM_WIN32)
1388 /* Emit a normal label too */
1389 fprintf (acfg->fp, "%s:\n", name);
1394 emit_string (MonoAotCompile *acfg, const char *value)
1396 emit_unset_mode (acfg);
1397 fprintf (acfg->fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
1401 emit_line (MonoAotCompile *acfg)
1403 emit_unset_mode (acfg);
1404 fprintf (acfg->fp, "\n");
1408 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
1410 emit_unset_mode (acfg);
1411 emit_section_change (acfg, ".text", 1);
1412 emit_global (acfg, name, FALSE);
1413 emit_label (acfg, name);
1414 emit_string (acfg, value);
1418 emit_alignment (MonoAotCompile *acfg, int size)
1420 emit_unset_mode (acfg);
1421 #if defined(__arm__)
1422 fprintf (acfg->fp, "\t.align %d\n", ilog2 (size));
1423 #elif defined(__ppc__) && defined(__MACH__)
1424 // the mach-o assembler specifies alignments as powers of 2.
1425 fprintf (acfg->fp, "\t.align %d\t; ilog2\n", ilog2(size));
1426 #elif defined(__powerpc__)
1427 /* ignore on linux/ppc */
1429 fprintf (acfg->fp, "\t.align %d\n", size);
1434 emit_pointer (MonoAotCompile *acfg, const char *target)
1436 emit_unset_mode (acfg);
1437 emit_alignment (acfg, sizeof (gpointer));
1438 #if defined(__x86_64__)
1439 fprintf (acfg->fp, "\t.quad %s\n", target ? target : "0");
1440 #elif defined(sparc) && SIZEOF_VOID_P == 8
1441 fprintf (acfg->fp, "\t.xword %s\n", target ? target : "0");
1443 fprintf (acfg->fp, "\t.long %s\n", target ? target : "0");
1447 static char *byte_to_str;
1450 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
1453 if (acfg->mode != EMIT_BYTE) {
1454 acfg->mode = EMIT_BYTE;
1455 acfg->col_count = 0;
1458 if (byte_to_str == NULL) {
1459 byte_to_str = g_new0 (char, 256 * 8);
1460 for (i = 0; i < 256; ++i) {
1461 sprintf (byte_to_str + (i * 8), ",%d", i);
1465 for (i = 0; i < size; ++i, ++acfg->col_count) {
1466 if ((acfg->col_count % 32) == 0)
1467 fprintf (acfg->fp, "\n\t.byte %d", buf [i]);
1469 fputs (byte_to_str + (buf [i] * 8), acfg->fp);
1474 emit_int16 (MonoAotCompile *acfg, int value)
1476 if (acfg->mode != EMIT_WORD) {
1477 acfg->mode = EMIT_WORD;
1478 acfg->col_count = 0;
1480 if ((acfg->col_count++ % 8) == 0)
1481 #if defined(__MACH__)
1482 fprintf (acfg->fp, "\n\t.short ");
1483 #elif defined(__arm__)
1484 /* FIXME: Use .hword on other archs as well */
1485 fprintf (acfg->fp, "\n\t.hword ");
1487 fprintf (acfg->fp, "\n\t.word ");
1490 fprintf (acfg->fp, ", ");
1491 fprintf (acfg->fp, "%d", value);
1495 emit_int32 (MonoAotCompile *acfg, int value)
1497 if (acfg->mode != EMIT_LONG) {
1498 acfg->mode = EMIT_LONG;
1499 acfg->col_count = 0;
1501 if ((acfg->col_count++ % 8) == 0)
1502 fprintf (acfg->fp, "\n\t.long ");
1504 fprintf (acfg->fp, ",");
1505 fprintf (acfg->fp, "%d", value);
1509 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
1511 if (acfg->mode != EMIT_LONG) {
1512 acfg->mode = EMIT_LONG;
1513 acfg->col_count = 0;
1515 if ((acfg->col_count++ % 8) == 0)
1516 fprintf (acfg->fp, "\n\t.long ");
1518 fprintf (acfg->fp, ",");
1520 fprintf (acfg->fp, "%s - %s + %d", end, start, offset);
1521 else if (offset < 0)
1522 fprintf (acfg->fp, "%s - %s %d", end, start, offset);
1524 fprintf (acfg->fp, "%s - %s", end, start);
1528 emit_zero_bytes (MonoAotCompile *acfg, int num)
1530 emit_unset_mode (acfg);
1531 #if defined(__MACH__)
1532 fprintf (acfg->fp, "\t.space %d\n", num);
1534 fprintf (acfg->fp, "\t.skip %d\n", num);
1539 emit_writeout (MonoAotCompile *acfg)
1541 char *command, *objfile;
1542 char *outfile_name, *tmp_outfile_name;
1546 #if defined(__x86_64__)
1547 #define AS_OPTIONS "--64"
1548 #elif defined(sparc) && SIZEOF_VOID_P == 8
1549 #define AS_OPTIONS "-xarch=v9"
1551 #define AS_OPTIONS ""
1554 if (acfg->aot_opts.asm_only) {
1555 printf ("Output file: '%s'.\n", acfg->tmpfname);
1556 if (acfg->aot_opts.static_link)
1557 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1561 if (acfg->aot_opts.static_link) {
1562 if (acfg->aot_opts.outfile)
1563 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1565 objfile = g_strdup_printf ("%s.o", acfg->image->name);
1567 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
1569 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
1570 printf ("Executing the native assembler: %s\n", command);
1571 if (system (command) != 0) {
1579 if (acfg->aot_opts.static_link) {
1580 printf ("Output file: '%s'.\n", objfile);
1581 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1586 if (acfg->aot_opts.outfile)
1587 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1589 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1591 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1594 command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
1595 #elif defined(__ppc__) && defined(__MACH__)
1596 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
1597 #elif defined(PLATFORM_WIN32)
1598 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
1600 if (acfg->aot_opts.no_dlsym) {
1602 * Need to link using gcc so our ctor function gets called.
1604 command = g_strdup_printf ("gcc -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1606 command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1609 printf ("Executing the native linker: %s\n", command);
1610 if (system (command) != 0) {
1611 g_free (tmp_outfile_name);
1612 g_free (outfile_name);
1620 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
1621 printf ("Stripping the binary: %s\n", com);
1625 rename (tmp_outfile_name, outfile_name);
1627 g_free (tmp_outfile_name);
1628 g_free (outfile_name);
1631 if (acfg->aot_opts.save_temps)
1632 printf ("Retained input file.\n");
1634 unlink (acfg->tmpfname);
1639 #endif /* ASM_WRITER */
1642 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
1644 if (acfg->aot_opts.no_dlsym) {
1645 g_ptr_array_add (acfg->globals, g_strdup (name));
1647 emit_global_inner (acfg, name, func);
1652 emit_byte (MonoAotCompile *acfg, guint8 val)
1654 emit_bytes (acfg, &val, 1);
1658 mono_get_field_token (MonoClassField *field)
1660 MonoClass *klass = field->parent;
1663 for (i = 0; i < klass->field.count; ++i) {
1664 if (field == &klass->fields [i])
1665 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1668 g_assert_not_reached ();
1673 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1677 //printf ("ENCODE: %d 0x%x.\n", value, value);
1680 * Same encoding as the one used in the metadata, extended to handle values
1681 * greater than 0x1fffffff.
1683 if ((value >= 0) && (value <= 127))
1685 else if ((value >= 0) && (value <= 16383)) {
1686 p [0] = 0x80 | (value >> 8);
1687 p [1] = value & 0xff;
1689 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1690 p [0] = (value >> 24) | 0xc0;
1691 p [1] = (value >> 16) & 0xff;
1692 p [2] = (value >> 8) & 0xff;
1693 p [3] = value & 0xff;
1698 p [1] = (value >> 24) & 0xff;
1699 p [2] = (value >> 16) & 0xff;
1700 p [3] = (value >> 8) & 0xff;
1701 p [4] = value & 0xff;
1709 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1713 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1717 index = g_hash_table_size (cfg->image_hash);
1718 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1719 g_ptr_array_add (cfg->image_table, image);
1725 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1728 MonoClass *k = NULL;
1730 /* FIXME: Search referenced images as well */
1731 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1732 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1737 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1738 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1744 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1749 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1750 * standard metadata encoding.
1753 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1757 if (klass->generic_class) {
1759 g_assert (klass->type_token);
1761 /* Find a typespec for a class if possible */
1762 token = find_typespec_for_class (acfg, klass);
1764 encode_value (token, p, &p);
1765 encode_value (get_image_index (acfg, acfg->image), p, &p);
1767 MonoClass *gclass = klass->generic_class->container_class;
1768 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1771 /* Encode it ourselves */
1773 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1774 encode_value (MONO_TYPE_GENERICINST, p, &p);
1775 encode_klass_ref (acfg, gclass, p, &p);
1776 encode_value (inst->type_argc, p, &p);
1777 for (i = 0; i < inst->type_argc; ++i)
1778 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1780 } else if (klass->type_token) {
1781 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1782 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1783 encode_value (get_image_index (acfg, klass->image), p, &p);
1784 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1785 MonoGenericParam *param = klass->byval_arg.data.generic_param;
1788 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1789 encode_value (klass->byval_arg.type, p, &p);
1791 encode_value (param->num, p, &p);
1793 g_assert (param->owner);
1794 encode_value (param->owner->is_method, p, &p);
1795 if (param->owner->is_method)
1796 encode_method_ref (acfg, param->owner->owner.method, p, &p);
1798 encode_klass_ref (acfg, param->owner->owner.klass, p, &p);
1801 g_assert (klass->rank > 0);
1802 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1803 encode_value (get_image_index (acfg, klass->image), p, &p);
1804 encode_value (klass->rank, p, &p);
1805 encode_klass_ref (acfg, klass->element_class, p, &p);
1811 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1813 guint32 token = mono_get_field_token (field);
1816 encode_klass_ref (cfg, field->parent, p, &p);
1817 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1818 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1823 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1827 MonoGenericInst *inst;
1829 /* Encode the context */
1830 inst = context->class_inst;
1831 encode_value (inst ? 1 : 0, p, &p);
1833 encode_value (inst->type_argc, p, &p);
1834 for (i = 0; i < inst->type_argc; ++i)
1835 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1837 inst = context->method_inst;
1838 encode_value (inst ? 1 : 0, p, &p);
1840 encode_value (inst->type_argc, p, &p);
1841 for (i = 0; i < inst->type_argc; ++i)
1842 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1848 #define MAX_IMAGE_INDEX 250
1851 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1853 guint32 image_index = get_image_index (acfg, method->klass->image);
1854 guint32 token = method->token;
1855 MonoJumpInfoToken *ji;
1858 g_assert (image_index < MAX_IMAGE_INDEX);
1860 /* Mark methods which can't use aot trampolines because they need the further
1861 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1863 if (method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
1864 encode_value ((252 << 24), p, &p);
1866 if (method->wrapper_type) {
1868 encode_value ((253 << 24), p, &p);
1870 encode_value (method->wrapper_type, p, &p);
1872 switch (method->wrapper_type) {
1873 case MONO_WRAPPER_REMOTING_INVOKE:
1874 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1875 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1878 m = mono_marshal_method_from_wrapper (method);
1880 encode_method_ref (acfg, m, p, &p);
1883 case MONO_WRAPPER_PROXY_ISINST:
1884 case MONO_WRAPPER_LDFLD:
1885 case MONO_WRAPPER_LDFLDA:
1886 case MONO_WRAPPER_STFLD:
1887 case MONO_WRAPPER_ISINST: {
1888 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1889 encode_klass_ref (acfg, proxy_class, p, &p);
1892 case MONO_WRAPPER_LDFLD_REMOTE:
1893 case MONO_WRAPPER_STFLD_REMOTE:
1895 case MONO_WRAPPER_ALLOC: {
1896 int alloc_type = mono_gc_get_managed_allocator_type (method);
1897 g_assert (alloc_type != -1);
1898 encode_value (alloc_type, p, &p);
1901 case MONO_WRAPPER_STELEMREF:
1902 case MONO_WRAPPER_MONITOR_FAST_ENTER:
1903 case MONO_WRAPPER_MONITOR_FAST_EXIT:
1905 case MONO_WRAPPER_STATIC_RGCTX_INVOKE: {
1908 m = mono_marshal_method_from_wrapper (method);
1910 encode_method_ref (acfg, m, p, &p);
1914 g_assert_not_reached ();
1916 } else if (mono_method_signature (method)->is_inflated) {
1918 * This is a generic method, find the original token which referenced it and
1920 * Obtain the token from information recorded by the JIT.
1922 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1924 image_index = get_image_index (acfg, ji->image);
1925 g_assert (image_index < MAX_IMAGE_INDEX);
1929 encode_value ((255 << 24), p, &p);
1930 encode_value (image_index, p, &p);
1931 encode_value (token, p, &p);
1933 MonoMethod *declaring;
1934 MonoGenericContext *context = mono_method_get_context (method);
1936 g_assert (method->is_inflated);
1937 declaring = ((MonoMethodInflated*)method)->declaring;
1940 * This might be a non-generic method of a generic instance, which
1941 * doesn't have a token since the reference is generated by the JIT
1942 * like Nullable:Box/Unbox, or by generic sharing.
1946 encode_value ((254 << 24), p, &p);
1947 /* Encode the klass */
1948 encode_klass_ref (acfg, method->klass, p, &p);
1949 /* Encode the method */
1950 image_index = get_image_index (acfg, method->klass->image);
1951 g_assert (image_index < MAX_IMAGE_INDEX);
1952 g_assert (declaring->token);
1953 token = declaring->token;
1954 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1955 encode_value (image_index, p, &p);
1956 encode_value (token, p, &p);
1957 encode_generic_context (acfg, context, p, &p);
1959 } else if (token == 0) {
1960 /* This might be a method of a constructed type like int[,].Set */
1961 /* Obtain the token from information recorded by the JIT */
1962 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1964 image_index = get_image_index (acfg, ji->image);
1965 g_assert (image_index < MAX_IMAGE_INDEX);
1969 encode_value ((255 << 24), p, &p);
1970 encode_value (image_index, p, &p);
1971 encode_value (token, p, &p);
1973 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1974 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1980 compare_patches (gconstpointer a, gconstpointer b)
1984 i = (*(MonoJumpInfo**)a)->ip.i;
1985 j = (*(MonoJumpInfo**)b)->ip.i;
1999 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2002 static inline gboolean
2003 is_plt_patch (MonoJumpInfo *patch_info)
2005 switch (patch_info->type) {
2006 case MONO_PATCH_INFO_METHOD:
2007 case MONO_PATCH_INFO_INTERNAL_METHOD:
2008 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2009 case MONO_PATCH_INFO_CLASS_INIT:
2010 case MONO_PATCH_INFO_RGCTX_FETCH:
2011 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2019 * is_shared_got_patch:
2021 * Return whenever PATCH_INFO refers to a patch which needs a shared GOT
2023 * Keep it in sync with the version in aot-runtime.c.
2025 static inline gboolean
2026 is_shared_got_patch (MonoJumpInfo *patch_info)
2028 switch (patch_info->type) {
2029 case MONO_PATCH_INFO_VTABLE:
2030 case MONO_PATCH_INFO_CLASS:
2031 case MONO_PATCH_INFO_IID:
2032 case MONO_PATCH_INFO_ADJUSTED_IID:
2033 case MONO_PATCH_INFO_FIELD:
2034 case MONO_PATCH_INFO_SFLDA:
2035 case MONO_PATCH_INFO_DECLSEC:
2036 case MONO_PATCH_INFO_LDTOKEN:
2037 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2038 case MONO_PATCH_INFO_RVA:
2039 case MONO_PATCH_INFO_METHODCONST:
2047 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2051 if (is_plt_patch (patch_info)) {
2052 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
2057 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2059 res = acfg->plt_offset;
2060 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
2061 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
2062 acfg->plt_offset ++;
2072 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2073 * JI could be found if it exists, otherwise allocates a new one.
2076 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2080 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
2082 return got_offset - 1;
2084 got_offset = acfg->got_offset;
2085 acfg->got_offset ++;
2087 acfg->stats.got_slots ++;
2088 acfg->stats.got_slot_types [ji->type] ++;
2094 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2099 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
2100 got_offset = get_got_offset (acfg, ji);
2101 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
2102 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
2103 g_ptr_array_add (acfg->shared_patches, copy);
2106 return get_got_offset (acfg, ji);
2109 /* Add a method to the list of methods which need to be emitted */
2111 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
2113 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2114 g_ptr_array_add (acfg->methods, method);
2115 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2116 acfg->nmethods = acfg->methods->len + 1;
2121 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2123 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2131 add_method (MonoAotCompile *acfg, MonoMethod *method)
2135 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2139 index = acfg->method_index;
2140 add_method_with_index (acfg, method, index);
2142 /* FIXME: Fix quadratic behavior */
2143 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2145 acfg->method_index ++;
2151 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2155 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2158 add_method (acfg, method);
2159 g_ptr_array_add (acfg->extra_methods, method);
2163 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2165 MonoAotCompile *acfg = user_data;
2166 MonoJitICallInfo *callinfo = value;
2167 MonoMethod *wrapper;
2173 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2174 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2177 add_method (acfg, wrapper);
2181 get_runtime_invoke_sig (MonoMethodSignature *sig)
2183 MonoMethodBuilder *mb;
2186 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2187 m = mono_mb_create_method (mb, sig, 16);
2188 return mono_marshal_get_runtime_invoke (m);
2192 add_wrappers (MonoAotCompile *acfg)
2194 MonoMethod *method, *m;
2195 int i, j, nallocators;
2196 MonoMethodSignature *sig, *csig;
2200 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2201 * so there is only one wrapper of a given type, or inlining their contents into their
2206 * FIXME: This depends on the fact that different wrappers have different
2210 /* FIXME: Collect these automatically */
2212 /* Runtime invoke wrappers */
2214 /* void runtime-invoke () [.cctor] */
2215 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2216 csig->ret = &mono_defaults.void_class->byval_arg;
2217 add_method (acfg, get_runtime_invoke_sig (csig));
2219 /* void runtime-invoke () [Finalize] */
2220 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2222 csig->ret = &mono_defaults.void_class->byval_arg;
2223 add_method (acfg, get_runtime_invoke_sig (csig));
2225 /* void runtime-invoke (string) [exception ctor] */
2226 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2228 csig->ret = &mono_defaults.void_class->byval_arg;
2229 csig->params [0] = &mono_defaults.string_class->byval_arg;
2230 add_method (acfg, get_runtime_invoke_sig (csig));
2232 /* void runtime-invoke (string, string) [exception ctor] */
2233 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2235 csig->ret = &mono_defaults.void_class->byval_arg;
2236 csig->params [0] = &mono_defaults.string_class->byval_arg;
2237 csig->params [1] = &mono_defaults.string_class->byval_arg;
2238 add_method (acfg, get_runtime_invoke_sig (csig));
2240 /* string runtime-invoke () [Exception.ToString ()] */
2241 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2243 csig->ret = &mono_defaults.string_class->byval_arg;
2244 add_method (acfg, get_runtime_invoke_sig (csig));
2246 /* void runtime-invoke (string, Exception) [exception ctor] */
2247 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2249 csig->ret = &mono_defaults.void_class->byval_arg;
2250 csig->params [0] = &mono_defaults.string_class->byval_arg;
2251 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2252 add_method (acfg, get_runtime_invoke_sig (csig));
2254 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2255 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2257 csig->ret = &(mono_class_from_name (
2258 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2259 csig->params [0] = &mono_defaults.string_class->byval_arg;
2260 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2261 add_method (acfg, get_runtime_invoke_sig (csig));
2263 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2265 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2266 gboolean skip = FALSE;
2268 method = mono_get_method (acfg->image, token, NULL);
2270 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2271 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2272 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2275 if (method->is_generic || method->klass->generic_container)
2278 /* Skip methods which can not be handled by get_runtime_invoke () */
2279 sig = mono_method_signature (method);
2280 if ((sig->ret->type == MONO_TYPE_PTR) ||
2281 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2284 for (j = 0; j < sig->param_count; j++) {
2285 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2290 add_method (acfg, mono_marshal_get_runtime_invoke (method));
2293 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2294 MonoMethodDesc *desc;
2295 MonoMethod *orig_method;
2297 /* JIT icall wrappers */
2298 /* FIXME: locking */
2299 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2301 /* Managed Allocators */
2302 nallocators = mono_gc_get_managed_allocator_types ();
2303 for (i = 0; i < nallocators; ++i) {
2304 m = mono_gc_get_managed_allocator_by_type (i);
2306 add_method (acfg, m);
2310 add_method (acfg, mono_marshal_get_stelemref ());
2312 /* Monitor Enter/Exit */
2313 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2314 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2315 g_assert (orig_method);
2316 mono_method_desc_free (desc);
2317 add_method (acfg, mono_monitor_get_fast_path (orig_method));
2319 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2320 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2321 g_assert (orig_method);
2322 mono_method_desc_free (desc);
2323 add_method (acfg, mono_monitor_get_fast_path (orig_method));
2326 /* remoting-invoke wrappers */
2327 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2328 MonoMethodSignature *sig;
2330 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2331 method = mono_get_method (acfg->image, token, NULL);
2333 sig = mono_method_signature (method);
2335 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
2336 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2337 m = mono_marshal_get_remoting_invoke_with_check (method);
2339 add_method (acfg, m);
2343 /* delegate-invoke wrappers */
2344 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2347 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2348 klass = mono_class_get (acfg->image, token);
2350 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2351 method = mono_get_delegate_invoke (klass);
2353 m = mono_marshal_get_delegate_invoke (method, NULL);
2355 add_method (acfg, m);
2360 /* static rgctx wrappers */
2361 /* FIXME: Each wrapper belongs to a given instantiation of a generic method */
2362 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2363 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2364 method = mono_get_method (acfg->image, token, NULL);
2366 if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
2367 (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
2368 mono_class_generic_sharing_enabled (method->klass) &&
2369 mono_method_is_generic_sharable_impl (method, FALSE)) {
2370 m = mono_marshal_get_static_rgctx_invoke (method);
2371 add_method (acfg, m);
2378 has_type_vars (MonoClass *klass)
2380 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2383 return has_type_vars (klass->element_class);
2384 if (klass->generic_class) {
2385 MonoGenericContext *context = &klass->generic_class->context;
2386 if (context->class_inst) {
2389 for (i = 0; i < context->class_inst->type_argc; ++i)
2390 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2398 method_has_type_vars (MonoMethod *method)
2400 if (has_type_vars (method->klass))
2403 if (method->is_inflated) {
2404 MonoGenericContext *context = mono_method_get_context (method);
2405 if (context->method_inst) {
2408 for (i = 0; i < context->method_inst->type_argc; ++i)
2409 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2417 * add_generic_instances:
2419 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2422 add_generic_instances (MonoAotCompile *acfg)
2427 MonoGenericContext *context;
2429 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2430 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2431 method = mono_get_method (acfg->image, token, NULL);
2433 context = mono_method_get_context (method);
2434 if (context && ((context->class_inst && context->class_inst->is_open) ||
2435 (context->method_inst && context->method_inst->is_open)))
2438 if (method->klass->image != acfg->image)
2441 if (mono_method_is_generic_sharable_impl (method, FALSE))
2445 add_extra_method (acfg, method);
2448 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2452 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2454 klass = mono_class_get (acfg->image, token);
2457 mono_class_init (klass);
2459 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2462 if (has_type_vars (klass))
2466 * Add rgctx wrappers for cctors since those are called by the runtime, so
2467 * there is no methodspec for them. This is needed even for shared classes,
2468 * since rgctx wrappers belong to inflated methods.
2470 method = mono_class_get_cctor (klass);
2472 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
2475 while ((method = mono_class_get_methods (klass, &iter))) {
2476 if (mono_method_is_generic_sharable_impl (method, FALSE))
2480 if (method->is_generic)
2485 * FIXME: Instances which are referenced by these methods are not added,
2486 * for example Array.Resize<int> for List<int>.Add ().
2488 add_extra_method (acfg, method);
2494 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2496 int i, pindex, start_index, method_index;
2498 MonoJumpInfo *patch_info;
2499 MonoMethodHeader *header;
2504 header = mono_method_get_header (method);
2506 method_index = get_method_index (acfg, method);
2509 /* Collect and sort relocations */
2510 patches = g_ptr_array_new ();
2511 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2512 g_ptr_array_add (patches, patch_info);
2513 g_ptr_array_sort (patches, compare_patches);
2516 for (i = 0; i < code_len; i++) {
2518 for (pindex = start_index; pindex < patches->len; ++pindex) {
2519 patch_info = g_ptr_array_index (patches, pindex);
2520 if (patch_info->ip.i >= i)
2524 #ifdef MONO_ARCH_AOT_SUPPORTED
2526 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2527 start_index = pindex;
2529 switch (patch_info->type) {
2530 case MONO_PATCH_INFO_NONE:
2532 case MONO_PATCH_INFO_GOT_OFFSET: {
2533 guint32 offset = mono_arch_get_patch_offset (code + i);
2534 emit_bytes (acfg, code + i, offset);
2535 emit_symbol_diff (acfg, "got", ".", offset);
2537 i += offset + 4 - 1;
2542 char *direct_call_target;
2544 if (!is_got_patch (patch_info->type))
2548 * If this patch is a call, try emitting a direct call instead of
2549 * through a PLT entry. This is possible if the called method is in
2550 * the same assembly and requires no initialization.
2552 direct_call_target = NULL;
2553 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
2554 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2556 gboolean direct_callable = TRUE;
2558 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2559 direct_callable = FALSE;
2560 if (direct_callable) {
2561 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2562 direct_call_target = g_strdup_printf (".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
2563 patch_info->type = MONO_PATCH_INFO_NONE;
2564 acfg->stats.direct_calls ++;
2568 acfg->stats.all_calls ++;
2571 if (!got_only && !direct_call_target) {
2572 int plt_offset = get_plt_offset (acfg, patch_info);
2573 if (plt_offset != -1) {
2574 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2575 direct_call_target = g_strdup_printf (".Lp_%d", plt_offset);
2577 /* Nullify the patch */
2578 patch_info->type = MONO_PATCH_INFO_NONE;
2582 if (direct_call_target) {
2583 #if defined(__i386__) || defined(__x86_64__)
2584 g_assert (code [i] == 0xe8);
2585 /* Need to make sure this is exactly 5 bytes long */
2586 emit_byte (acfg, '\xe8');
2587 emit_symbol_diff (acfg, direct_call_target, ".", -4);
2589 #elif defined(__arm__)
2590 #ifdef USE_BIN_WRITER
2591 /* FIXME: Can't encode this using the current symbol writer functions */
2592 g_assert_not_reached ();
2594 emit_unset_mode (acfg);
2595 fprintf (acfg->fp, "bl %s\n", direct_call_target);
2600 g_free (direct_call_target);
2602 got_slot = get_got_offset (acfg, patch_info);
2604 emit_bytes (acfg, code + i, mono_arch_get_patch_offset (code + i));
2606 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
2607 #elif defined(__i386__)
2608 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
2609 #elif defined(__arm__)
2610 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
2612 g_assert_not_reached ();
2615 i += mono_arch_get_patch_offset (code + i) + 4 - 1;
2621 #endif /* MONO_ARCH_AOT_SUPPORTED */
2624 emit_bytes (acfg, code + i, 1);
2629 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2635 int func_alignment = 16;
2636 MonoMethodHeader *header;
2638 method = cfg->orig_method;
2639 code = cfg->native_code;
2640 header = mono_method_get_header (method);
2642 method_index = get_method_index (acfg, method);
2644 /* Make the labels local */
2645 symbol = g_strdup_printf (".Lm_%x", method_index);
2647 emit_alignment (acfg, func_alignment);
2648 emit_label (acfg, symbol);
2649 if (acfg->aot_opts.write_symbols)
2650 emit_global (acfg, symbol, TRUE);
2652 if (cfg->verbose_level > 0)
2653 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2656 acfg->stats.code_size += cfg->code_len;
2658 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2660 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2668 * Encode PATCH_INFO into its disk representation.
2671 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2675 switch (patch_info->type) {
2676 case MONO_PATCH_INFO_NONE:
2678 case MONO_PATCH_INFO_IMAGE:
2679 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2681 case MONO_PATCH_INFO_METHOD_REL:
2682 encode_value ((gint)patch_info->data.offset, p, &p);
2684 case MONO_PATCH_INFO_SWITCH: {
2685 gpointer *table = (gpointer *)patch_info->data.table->table;
2688 encode_value (patch_info->data.table->table_size, p, &p);
2689 for (k = 0; k < patch_info->data.table->table_size; k++)
2690 encode_value ((int)(gssize)table [k], p, &p);
2693 case MONO_PATCH_INFO_METHODCONST:
2694 case MONO_PATCH_INFO_METHOD:
2695 case MONO_PATCH_INFO_METHOD_JUMP:
2696 case MONO_PATCH_INFO_ICALL_ADDR:
2697 case MONO_PATCH_INFO_METHOD_RGCTX:
2698 encode_method_ref (acfg, patch_info->data.method, p, &p);
2700 case MONO_PATCH_INFO_INTERNAL_METHOD:
2701 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2702 guint32 len = strlen (patch_info->data.name);
2704 encode_value (len, p, &p);
2706 memcpy (p, patch_info->data.name, len);
2711 case MONO_PATCH_INFO_LDSTR: {
2712 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2713 guint32 token = patch_info->data.token->token;
2714 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2715 encode_value (image_index, p, &p);
2716 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2719 case MONO_PATCH_INFO_RVA:
2720 case MONO_PATCH_INFO_DECLSEC:
2721 case MONO_PATCH_INFO_LDTOKEN:
2722 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2723 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2724 encode_value (patch_info->data.token->token, p, &p);
2725 encode_value (patch_info->data.token->has_context, p, &p);
2726 if (patch_info->data.token->has_context)
2727 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2729 case MONO_PATCH_INFO_EXC_NAME: {
2730 MonoClass *ex_class;
2733 mono_class_from_name (mono_defaults.exception_class->image,
2734 "System", patch_info->data.target);
2735 g_assert (ex_class);
2736 encode_klass_ref (acfg, ex_class, p, &p);
2739 case MONO_PATCH_INFO_R4:
2740 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2742 case MONO_PATCH_INFO_R8:
2743 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2744 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2746 case MONO_PATCH_INFO_VTABLE:
2747 case MONO_PATCH_INFO_CLASS:
2748 case MONO_PATCH_INFO_IID:
2749 case MONO_PATCH_INFO_ADJUSTED_IID:
2750 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2752 case MONO_PATCH_INFO_CLASS_INIT:
2753 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2754 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2756 case MONO_PATCH_INFO_FIELD:
2757 case MONO_PATCH_INFO_SFLDA:
2758 encode_field_info (acfg, patch_info->data.field, p, &p);
2760 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2762 case MONO_PATCH_INFO_RGCTX_FETCH: {
2763 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2765 encode_method_ref (acfg, entry->method, p, &p);
2766 encode_value (entry->in_mrgctx, p, &p);
2767 encode_value (entry->info_type, p, &p);
2768 encode_value (entry->data->type, p, &p);
2769 encode_patch (acfg, entry->data, p, &p);
2772 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2775 g_warning ("unable to handle jump info %d", patch_info->type);
2776 g_assert_not_reached ();
2783 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2786 guint32 last_offset, j, pindex;
2787 MonoJumpInfo *patch_info;
2789 encode_value (n_patches, p, &p);
2792 encode_value (first_got_offset, p, &p);
2794 /* First encode the type+position table */
2797 for (pindex = 0; pindex < patches->len; ++pindex) {
2799 patch_info = g_ptr_array_index (patches, pindex);
2801 if (patch_info->type == MONO_PATCH_INFO_NONE)
2806 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
2807 offset = patch_info->ip.i - last_offset;
2808 last_offset = patch_info->ip.i;
2810 /* Only the type is needed */
2811 *p = patch_info->type;
2815 /* Then encode the other info */
2816 for (pindex = 0; pindex < patches->len; ++pindex) {
2817 patch_info = g_ptr_array_index (patches, pindex);
2819 if (is_shared_got_patch (patch_info)) {
2820 guint32 offset = get_got_offset (acfg, patch_info);
2821 encode_value (offset, p, &p);
2823 encode_patch (acfg, patch_info, p, &p);
2831 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2835 int pindex, buf_size, n_patches;
2839 MonoJumpInfo *patch_info;
2840 MonoMethodHeader *header;
2841 guint32 method_index;
2843 guint32 first_got_offset;
2845 method = cfg->orig_method;
2846 code = cfg->native_code;
2847 header = mono_method_get_header (method);
2849 method_index = get_method_index (acfg, method);
2851 /* Make the labels local */
2852 symbol = g_strdup_printf (".Lm_%x_p", method_index);
2854 /* Sort relocations */
2855 patches = g_ptr_array_new ();
2856 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2857 g_ptr_array_add (patches, patch_info);
2858 g_ptr_array_sort (patches, compare_patches);
2860 first_got_offset = acfg->cfgs [method_index]->got_offset;
2862 /**********************/
2863 /* Encode method info */
2864 /**********************/
2866 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2867 p = buf = g_malloc (buf_size);
2869 if (mono_class_get_cctor (method->klass))
2870 encode_klass_ref (acfg, method->klass, p, &p);
2872 /* Not needed when loading the method */
2873 encode_value (0, p, &p);
2876 if (cfg->opt & MONO_OPT_SHARED) {
2877 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2878 for (l = cfg->ldstr_list; l; l = l->next) {
2879 encode_value ((long)l->data, p, &p);
2883 /* Used only in shared mode */
2884 g_assert (!cfg->ldstr_list);
2887 for (pindex = 0; pindex < patches->len; ++pindex) {
2888 patch_info = g_ptr_array_index (patches, pindex);
2890 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2891 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2892 patch_info->type = MONO_PATCH_INFO_NONE;
2897 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2898 /* Stored in a GOT slot initialized at module load time */
2899 patch_info->type = MONO_PATCH_INFO_NONE;
2903 if (is_plt_patch (patch_info)) {
2904 /* Calls are made through the PLT */
2905 patch_info->type = MONO_PATCH_INFO_NONE;
2913 g_assert (cfg->has_got_slots);
2915 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2917 acfg->stats.info_size += p - buf;
2919 /* Emit method info */
2921 emit_label (acfg, symbol);
2924 g_assert (p - buf < buf_size);
2925 emit_bytes (acfg, buf, p - buf);
2930 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2933 int k, buf_size, method_index;
2934 guint32 debug_info_size;
2937 MonoMethodHeader *header;
2938 guint8 *p, *buf, *debug_info;
2939 MonoJitInfo *jinfo = cfg->jit_info;
2941 method = cfg->orig_method;
2942 code = cfg->native_code;
2943 header = mono_method_get_header (method);
2945 method_index = get_method_index (acfg, method);
2947 /* Make the labels local */
2948 symbol = g_strdup_printf (".Le_%x_p", method_index);
2950 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2952 buf_size = header->num_clauses * 256 + debug_info_size + 128;
2953 p = buf = g_malloc (buf_size);
2955 encode_value (jinfo->code_size, p, &p);
2956 encode_value (jinfo->used_regs, p, &p);
2957 encode_value (jinfo->has_generic_jit_info, p, &p);
2959 /* Exception table */
2960 if (header->num_clauses) {
2961 for (k = 0; k < header->num_clauses; ++k) {
2962 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2964 encode_value (ei->exvar_offset, p, &p);
2966 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2967 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2969 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2970 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2971 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2975 if (jinfo->has_generic_jit_info) {
2976 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2978 encode_value (gi->has_this ? 1 : 0, p, &p);
2979 encode_value (gi->this_reg, p, &p);
2980 encode_value (gi->this_offset, p, &p);
2983 * Need to encode jinfo->method too, since it is not equal to 'method'
2984 * when using generic sharing.
2986 encode_method_ref (acfg, jinfo->method, p, &p);
2989 g_assert (debug_info_size < buf_size);
2991 encode_value (debug_info_size, p, &p);
2992 if (debug_info_size) {
2993 memcpy (p, debug_info, debug_info_size);
2994 p += debug_info_size;
2995 g_free (debug_info);
2998 acfg->stats.ex_info_size += p - buf;
3002 emit_label (acfg, symbol);
3005 g_assert (p - buf < buf_size);
3006 emit_bytes (acfg, buf, p - buf);
3011 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3013 MonoClass *klass = mono_class_get (acfg->image, token);
3017 gboolean no_special_static, cant_encode;
3018 gpointer iter = NULL;
3020 buf_size = 10240 + (klass->vtable_size * 16);
3021 p = buf = g_malloc (buf_size);
3025 mono_class_init (klass);
3027 mono_class_get_nested_types (klass, &iter);
3028 g_assert (klass->nested_classes_inited);
3030 mono_class_setup_vtable (klass);
3033 * Emit all the information which is required for creating vtables so
3034 * the runtime does not need to create the MonoMethod structures which
3035 * take up a lot of space.
3038 no_special_static = !mono_class_has_special_static_fields (klass);
3040 /* Check whenever we have enough info to encode the vtable */
3041 cant_encode = FALSE;
3042 for (i = 0; i < klass->vtable_size; ++i) {
3043 MonoMethod *cm = klass->vtable [i];
3045 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3049 if (klass->generic_container || cant_encode) {
3050 encode_value (-1, p, &p);
3052 encode_value (klass->vtable_size, p, &p);
3053 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);
3054 if (klass->has_cctor)
3055 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3056 if (klass->has_finalize)
3057 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3059 encode_value (klass->instance_size, p, &p);
3060 encode_value (mono_class_data_size (klass), p, &p);
3061 encode_value (klass->packing_size, p, &p);
3062 encode_value (klass->min_align, p, &p);
3064 for (i = 0; i < klass->vtable_size; ++i) {
3065 MonoMethod *cm = klass->vtable [i];
3068 encode_method_ref (acfg, cm, p, &p);
3070 encode_value (0, p, &p);
3074 acfg->stats.class_info_size += p - buf;
3077 symbol = g_strdup_printf (".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
3078 emit_label (acfg, symbol);
3081 g_assert (p - buf < buf_size);
3082 emit_bytes (acfg, buf, p - buf);
3087 * Calls made from AOTed code are routed through a table of jumps similar to the
3088 * ELF PLT (Program Linkage Table). The differences are the following:
3089 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3090 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3091 * jumps. This means the jumps need to be patched when the address of the callee is
3092 * known. Initially the PLT entries jump to code which transfers control to the
3093 * AOT runtime through the first PLT entry.
3096 emit_plt (MonoAotCompile *acfg)
3101 guint32 *plt_info_offsets;
3104 * Encode info need to resolve PLT entries.
3106 buf_size = acfg->plt_offset * 128;
3107 p = buf = g_malloc (buf_size);
3109 plt_info_offsets = g_new0 (guint32, acfg->plt_offset);
3111 for (i = 1; i < acfg->plt_offset; ++i) {
3112 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3114 plt_info_offsets [i] = p - buf;
3115 encode_value (patch_info->type, p, &p);
3116 encode_patch (acfg, patch_info, p, &p);
3120 symbol = g_strdup_printf ("plt");
3122 /* This section will be made read-write by the AOT loader */
3123 emit_section_change (acfg, ".text", 0);
3124 emit_global (acfg, symbol, TRUE);
3126 emit_alignment (acfg, PAGESIZE);
3128 emit_label (acfg, symbol);
3131 #if defined(USE_BIN_WRITER) && defined(__arm__)
3133 g_assert_not_reached ();
3136 for (i = 0; i < acfg->plt_offset; ++i) {
3139 label = g_strdup_printf (".Lp_%d", i);
3140 emit_label (acfg, label);
3144 * The first plt entry is used to transfer code to the AOT loader.
3147 #if defined(__i386__)
3149 /* It is filled up during loading by the AOT loader. */
3150 emit_zero_bytes (acfg, 16);
3152 /* Need to make sure this is 9 bytes long */
3153 emit_byte (acfg, '\xe9');
3154 emit_symbol_diff (acfg, "plt", ".", -4);
3155 emit_int32 (acfg, plt_info_offsets [i]);
3157 #elif defined(__x86_64__)
3159 * We can't emit jumps because they are 32 bits only so they can't be patched.
3160 * So we emit a jump table instead whose entries are patched by the AOT loader to
3161 * point to .Lpd entries. ELF stores these in the GOT too, but we don't, since
3162 * methods with GOT entries can't be called directly.
3163 * We also emit the default PLT code here since the PLT code will not be patched.
3164 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
3166 /* jmpq *<offset>(%rip) */
3167 emit_byte (acfg, '\xff');
3168 emit_byte (acfg, '\x25');
3169 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)) -4);
3170 /* Used by mono_aot_get_plt_info_offset */
3171 emit_int32 (acfg, plt_info_offsets [i]);
3172 #elif defined(__arm__)
3174 * - optimize OP_AOTCONST implementation
3175 * - optimize the PLT entries
3176 * - optimize SWITCH AOT implementation
3177 * - implement IMT support
3179 emit_unset_mode (acfg);
3180 fprintf (acfg->fp, "\tldr ip, [pc, #4]\n");
3181 fprintf (acfg->fp, "\tadd ip, pc, ip\n");
3182 fprintf (acfg->fp, "\tldr pc, [ip, #0]\n");
3183 emit_symbol_diff (acfg, "plt_jump_table", ".", (i * sizeof (gpointer)));
3184 /* Used by mono_aot_get_plt_info_offset */
3185 #if defined(__MACH__)
3186 fprintf (acfg->fp, "\n\t.long %d\n", plt_info_offsets [i]);
3188 fprintf (acfg->fp, "\n\t.word %d\n", plt_info_offsets [i]);
3192 g_assert_not_reached ();
3196 g_free (plt_info_offsets);
3198 symbol = g_strdup_printf ("plt_end");
3199 emit_global (acfg, symbol, TRUE);
3200 emit_label (acfg, symbol);
3204 symbol = g_strdup_printf ("plt_info");
3205 emit_global (acfg, symbol, FALSE);
3206 emit_label (acfg, symbol);
3209 g_assert (p - buf < buf_size);
3210 emit_bytes (acfg, buf, p - buf);
3213 symbol = g_strdup_printf ("plt_jump_table_addr");
3214 emit_section_change (acfg, ".data", 0);
3215 emit_global (acfg, symbol, FALSE);
3216 emit_alignment (acfg, 8);
3217 emit_label (acfg, symbol);
3218 emit_pointer (acfg, "plt_jump_table");
3221 symbol = g_strdup_printf ("plt_jump_table_size");
3222 emit_section_change (acfg, ".data", 0);
3223 emit_global (acfg, symbol, FALSE);
3224 emit_alignment (acfg, 8);
3225 emit_label (acfg, symbol);
3226 emit_symbol_diff (acfg, "plt_jump_table_end", "plt_jump_table", 0);
3229 /* Don't make this a global so accesses don't need relocations */
3230 symbol = g_strdup_printf ("plt_jump_table");
3231 emit_section_change (acfg, ".bss", 0);
3232 emit_label (acfg, symbol);
3235 #if defined(__x86_64__) || defined(__arm__)
3236 emit_zero_bytes (acfg, (int)(acfg->plt_offset * sizeof (gpointer)));
3239 symbol = g_strdup_printf ("plt_jump_table_end");
3240 emit_label (acfg, symbol);
3244 static G_GNUC_UNUSED void
3245 emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code,
3246 guint32 code_size, int got_offset, MonoJumpInfo *ji)
3250 MonoJumpInfo *patch_info;
3256 symbol = g_strdup_printf ("%s", name);
3258 emit_section_change (acfg, ".text", 0);
3259 emit_global (acfg, symbol, TRUE);
3260 emit_alignment (acfg, 16);
3261 emit_label (acfg, symbol);
3265 * The code should access everything through the GOT, so we pass
3268 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3272 /* Sort relocations */
3273 patches = g_ptr_array_new ();
3274 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3275 g_ptr_array_add (patches, patch_info);
3276 g_ptr_array_sort (patches, compare_patches);
3278 buf_size = patches->len * 128 + 128;
3279 buf = g_malloc (buf_size);
3282 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3283 g_assert (p - buf < buf_size);
3285 symbol = g_strdup_printf ("%s_p", name);
3287 emit_section_change (acfg, ".text", 0);
3288 emit_global (acfg, symbol, FALSE);
3289 emit_label (acfg, symbol);
3292 emit_bytes (acfg, buf, p - buf);
3296 * When running in aot-only mode, we can't create trampolines at runtime, so we create
3297 * a few, and save them in the AOT file. Normal trampolines embed their argument as a
3298 * literal inside the trampoline code, we can't do that here, so instead we embed an offset
3299 * which needs to be added to the trampoline address to get the address of the GOT slot
3300 * which contains the argument value.
3301 * The generated trampolines jump to the generic trampolines using another GOT slot, which
3302 * will be setup by the AOT loader to point to the generic trampoline code of the given
3306 emit_trampolines (MonoAotCompile *acfg)
3310 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3317 if (!acfg->aot_opts.full_aot)
3320 g_assert (acfg->image->assembly);
3322 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3323 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3324 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3326 * Emit the generic trampolines.
3328 * We could save some code by treating the generic trampolines as a wrapper
3329 * method, but that approach has its own complexities, so we choose the simpler
3332 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3333 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, TRUE);
3335 /* Emit trampoline code */
3337 symbol = g_strdup_printf ("generic_trampoline_%d", tramp_type);
3339 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3344 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3345 emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL);
3347 /* Emit the exception related code pieces */
3348 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3349 emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji);
3350 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3351 emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji);
3352 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3353 emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji);
3354 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3355 emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji);
3356 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3357 emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji);
3358 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3359 emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji);
3362 for (i = 0; i < 128; ++i) {
3365 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3366 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3367 symbol = g_strdup_printf ("rgctx_fetch_trampoline_%u", offset);
3368 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3371 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3372 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3373 symbol = g_strdup_printf ("rgctx_fetch_trampoline_%u", offset);
3374 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3381 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3385 /* Reserve some entries at the end of the GOT for our use */
3386 acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
3388 symbol = g_strdup_printf ("trampolines");
3390 emit_section_change (acfg, ".text", 0);
3391 emit_global (acfg, symbol, TRUE);
3392 emit_alignment (acfg, 16);
3393 emit_label (acfg, symbol);
3395 for (i = 0; i < acfg->num_aot_trampolines; ++i) {
3396 offset = acfg->got_offset + (i * 2);
3399 * The trampolines created here are variations of the specific
3400 * trampolines created in mono_arch_create_specific_trampoline (). The
3402 * - the generic trampoline address is taken from a got slot.
3403 * - the offset of the got slot where the trampoline argument is stored
3404 * is embedded in the instruction stream, and the generic trampoline
3405 * can load the argument by loading the offset, adding it to the
3406 * address of the trampoline to get the address of the got slot, and
3407 * loading the argument from the there.
3409 #if defined(__x86_64__)
3410 /* This should be exactly 16 bytes long */
3411 /* It should work together with the generic trampoline code in tramp-amd64.c */
3412 /* call *<offset>(%rip) */
3413 emit_byte (acfg, '\x41');
3414 emit_byte (acfg, '\xff');
3415 emit_byte (acfg, '\x15');
3416 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
3417 /* This should be relative to the start of the trampoline */
3418 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
3419 emit_zero_bytes (acfg, 5);
3420 #elif defined(__arm__)
3424 /* Generate the trampoline code */
3425 /* This should be exactly 28 bytes long */
3428 ARM_PUSH (code, 0x5fff);
3429 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
3430 /* Load the value from the GOT */
3431 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
3433 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
3434 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
3436 g_assert (code - buf == 20);
3439 emit_bytes (acfg, buf, code - buf);
3440 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
3441 emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
3444 g_assert_not_reached ();
3449 /* Unbox trampolines */
3451 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3453 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3457 method = mono_get_method (acfg->image, token, NULL);
3459 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3460 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
3463 symbol = g_strdup_printf ("unbox_trampoline_%d", i);
3465 emit_section_change (acfg, ".text", 0);
3466 emit_global (acfg, symbol, TRUE);
3467 emit_label (acfg, symbol);
3469 call_target = g_strdup_printf (".Lm_%x", get_method_index (acfg, cfg->orig_method));
3471 #if defined(__x86_64__)
3476 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (cfg->orig_method), cfg->generic_sharing_context, NULL);
3478 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
3480 emit_bytes (acfg, buf, code - buf);
3482 emit_byte (acfg, '\xe9');
3483 emit_symbol_diff (acfg, call_target, ".", -4);
3485 #elif defined(__arm__)
3492 if (MONO_TYPE_ISSTRUCT (mono_method_signature (cfg->orig_method)->ret))
3495 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
3497 emit_bytes (acfg, buf, code - buf);
3498 /* jump to method */
3499 #if defined(USE_BIN_WRITER)
3501 g_assert_not_reached ();
3503 fprintf (acfg->fp, "\n\tb %s\n", call_target);
3506 g_assert_not_reached ();
3510 symbol = g_strdup_printf ("trampolines_info");
3512 emit_section_change (acfg, ".text", 0);
3513 emit_global (acfg, symbol, TRUE);
3514 emit_alignment (acfg, PAGESIZE);
3515 emit_label (acfg, symbol);
3517 emit_int32 (acfg, acfg->num_aot_trampolines);
3518 emit_int32 (acfg, acfg->got_offset);
3522 str_begins_with (const char *str1, const char *str2)
3524 int len = strlen (str2);
3525 return strncmp (str1, str2, len) == 0;
3529 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3531 gchar **args, **ptr;
3533 memset (opts, 0, sizeof (*opts));
3535 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3536 for (ptr = args; ptr && *ptr; ptr ++) {
3537 const char *arg = *ptr;
3539 if (str_begins_with (arg, "outfile=")) {
3540 opts->outfile = g_strdup (arg + strlen ("outfile="));
3541 } else if (str_begins_with (arg, "save-temps")) {
3542 opts->save_temps = TRUE;
3543 } else if (str_begins_with (arg, "keep-temps")) {
3544 opts->save_temps = TRUE;
3545 } else if (str_begins_with (arg, "write-symbols")) {
3546 opts->write_symbols = TRUE;
3547 } else if (str_begins_with (arg, "metadata-only")) {
3548 opts->metadata_only = TRUE;
3549 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3550 opts->bind_to_runtime_version = TRUE;
3551 } else if (str_begins_with (arg, "full")) {
3552 opts->full_aot = TRUE;
3554 * The no-dlsym option is only useful on the iphone, and even there,
3555 * do to other limitations of the dynamic linker, it doesn't seem to
3556 * work. So disable it for now so we don't have to support it.
3559 } else if (str_begins_with (arg, "no-dlsym")) {
3560 opts->no_dlsym = TRUE;
3562 } else if (str_begins_with (arg, "static")) {
3563 opts->static_link = TRUE;
3564 opts->no_dlsym = TRUE;
3565 } else if (str_begins_with (arg, "asmonly")) {
3566 opts->asm_only = TRUE;
3568 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3577 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3579 MonoMethod *method = (MonoMethod*)key;
3580 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3581 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3582 MonoAotCompile *acfg = user_data;
3584 new_ji->image = ji->image;
3585 new_ji->token = ji->token;
3586 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3590 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3593 MonoJumpInfo *patch_info;
3596 MonoMethod *wrapped;
3598 if (acfg->aot_opts.metadata_only)
3601 index = get_method_index (acfg, method);
3603 /* fixme: maybe we can also precompile wrapper methods */
3604 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3605 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3606 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3607 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3611 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3614 wrapped = mono_marshal_method_from_wrapper (method);
3615 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3616 // FIXME: The wrapper should be generic too, but it is not
3619 acfg->stats.mcount++;
3621 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3623 * FIXME: Enabling this causes virtual-sync.exe to fail, since the trampoline
3624 * code can't determine that it needs to insert a sync wrapper in the AOT case.
3630 if (method->is_generic || method->klass->generic_container) {
3631 acfg->stats.genericcount ++;
3636 if (acfg->aot_opts.full_aot)
3637 mono_use_imt = FALSE;
3640 * Since these methods are the only ones which are compiled with
3641 * AOT support, and they are not used by runtime startup/shutdown code,
3642 * the runtime will not see AOT methods during AOT compilation,so it
3643 * does not need to support them by creating a fake GOT etc.
3645 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3646 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3647 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3648 acfg->stats.genericcount ++;
3651 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3652 /* Let the exception happen at runtime */
3656 if (cfg->disable_aot) {
3657 //printf ("Skip (other): %s\n", mono_method_full_name (method, TRUE));
3658 acfg->stats.ocount++;
3659 mono_destroy_compile (cfg);
3663 /* Nullify patches which need no aot processing */
3664 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3665 switch (patch_info->type) {
3666 case MONO_PATCH_INFO_LABEL:
3667 case MONO_PATCH_INFO_BB:
3668 patch_info->type = MONO_PATCH_INFO_NONE;
3675 /* Collect method->token associations from the cfg */
3676 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3679 * Check for absolute addresses.
3682 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3683 switch (patch_info->type) {
3684 case MONO_PATCH_INFO_ABS:
3685 /* unable to handle this */
3686 //printf ("Skip (abs addr): %s %d\n", mono_method_full_name (method, TRUE), patch_info->type);
3695 acfg->stats.abscount++;
3696 mono_destroy_compile (cfg);
3701 * Check for wrapper methods we can't encode.
3704 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3705 if ((patch_info->type == MONO_PATCH_INFO_METHODCONST) || (patch_info->type == MONO_PATCH_INFO_METHOD)) {
3706 switch (patch_info->data.method->wrapper_type) {
3707 case MONO_WRAPPER_NONE:
3708 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3709 case MONO_WRAPPER_XDOMAIN_INVOKE:
3710 case MONO_WRAPPER_STFLD:
3711 case MONO_WRAPPER_LDFLD:
3712 case MONO_WRAPPER_LDFLDA:
3713 case MONO_WRAPPER_LDFLD_REMOTE:
3714 case MONO_WRAPPER_STFLD_REMOTE:
3715 case MONO_WRAPPER_STELEMREF:
3716 case MONO_WRAPPER_ISINST:
3717 case MONO_WRAPPER_PROXY_ISINST:
3718 case MONO_WRAPPER_ALLOC:
3719 case MONO_WRAPPER_REMOTING_INVOKE:
3720 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
3721 case MONO_WRAPPER_MONITOR_FAST_ENTER:
3722 case MONO_WRAPPER_MONITOR_FAST_EXIT:
3725 /* unable to handle this */
3726 //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));
3730 } else if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH) {
3731 MonoJumpInfo *child = patch_info->data.rgctx_entry->data;
3733 if (child->type == MONO_PATCH_INFO_METHODCONST) {
3734 switch (child->data.method->wrapper_type) {
3735 case MONO_WRAPPER_NONE:
3736 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
3746 acfg->stats.wrappercount++;
3747 mono_destroy_compile (cfg);
3752 * Check for methods/klasses we can't encode.
3755 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3756 switch (patch_info->type) {
3757 case MONO_PATCH_INFO_METHOD:
3758 case MONO_PATCH_INFO_METHODCONST:
3759 if (patch_info->data.method->wrapper_type)
3761 if (!patch_info->data.method->token) {
3762 /* The method is part of a constructed type like Int[,].Set (). */
3763 if (!g_hash_table_lookup (acfg->token_info_hash, patch_info->data.method))
3767 case MONO_PATCH_INFO_VTABLE:
3768 case MONO_PATCH_INFO_CLASS_INIT:
3769 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3770 case MONO_PATCH_INFO_CLASS:
3771 case MONO_PATCH_INFO_IID:
3772 case MONO_PATCH_INFO_ADJUSTED_IID:
3773 if (!patch_info->data.klass->type_token)
3774 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))
3783 acfg->stats.ocount++;
3784 mono_destroy_compile (cfg);
3788 /* Adds generic instances referenced by this method */
3789 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3790 switch (patch_info->type) {
3791 case MONO_PATCH_INFO_METHOD: {
3792 MonoMethod *m = patch_info->data.method;
3793 if (m->is_inflated) {
3794 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3795 mono_method_is_generic_sharable_impl (m, FALSE)) &&
3796 !method_has_type_vars (m))
3797 add_extra_method (acfg, m);
3806 /* Determine whenever the method has GOT slots */
3807 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3808 switch (patch_info->type) {
3809 case MONO_PATCH_INFO_GOT_OFFSET:
3810 case MONO_PATCH_INFO_NONE:
3812 case MONO_PATCH_INFO_IMAGE:
3813 /* The assembly is stored in GOT slot 0 */
3814 if (patch_info->data.image != acfg->image)
3815 cfg->has_got_slots = TRUE;
3818 if (!is_plt_patch (patch_info))
3819 cfg->has_got_slots = TRUE;
3824 if (!cfg->has_got_slots)
3825 acfg->stats.methods_without_got_slots ++;
3827 /* Make a copy of the patch info which is in the mempool */
3829 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3831 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3832 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3835 patches = new_patch_info;
3837 patches_end->next = new_patch_info;
3838 patches_end = new_patch_info;
3840 cfg->patch_info = patches;
3843 /* Free some fields used by cfg to conserve memory */
3844 mono_mempool_destroy (cfg->mempool);
3845 cfg->mempool = NULL;
3846 g_free (cfg->varinfo);
3847 cfg->varinfo = NULL;
3851 mono_regstate_free (cfg->rs);
3855 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
3857 while (index >= acfg->cfgs_size) {
3858 MonoCompile **new_cfgs;
3861 new_size = acfg->cfgs_size * 2;
3862 new_cfgs = g_new0 (MonoCompile*, new_size);
3863 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3864 g_free (acfg->cfgs);
3865 acfg->cfgs = new_cfgs;
3866 acfg->cfgs_size = new_size;
3868 acfg->cfgs [index] = cfg;
3870 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3872 if (cfg->orig_method->wrapper_type)
3873 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3875 acfg->stats.ccount++;
3879 load_profile_files (MonoAotCompile *acfg)
3883 int file_index, res, method_index, i;
3890 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);
3892 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3897 infile = fopen (tmp, "r");
3900 printf ("Using profile data file '%s'\n", tmp);
3905 res = fscanf (infile, "%32s\n", ver);
3906 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3907 printf ("Profile file has wrong version or invalid.\n");
3913 res = fscanf (infile, "%d\n", &token);
3917 method_index = mono_metadata_token_index (token) - 1;
3919 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3920 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3925 /* Add missing methods */
3927 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3928 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3929 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3931 unordered = g_list_reverse (unordered);
3932 if (acfg->method_order)
3933 g_list_last (acfg->method_order)->next = unordered;
3935 acfg->method_order = unordered;
3941 * Collect all patches which have shared GOT entries and alloc entries for them. The
3942 * rest will get entries allocated during emit_code ().
3945 alloc_got_slots (MonoAotCompile *acfg)
3951 /* Slot 0 is reserved for the address of the current assembly */
3952 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3953 ji->type = MONO_PATCH_INFO_IMAGE;
3954 ji->data.image = acfg->image;
3956 get_shared_got_offset (acfg, ji);
3958 for (l = acfg->method_order; l != NULL; l = l->next) {
3959 i = GPOINTER_TO_UINT (l->data);
3961 if (acfg->cfgs [i]) {
3962 MonoCompile *cfg = acfg->cfgs [i];
3964 for (ji = cfg->patch_info; ji; ji = ji->next) {
3965 if (is_shared_got_patch (ji))
3966 get_shared_got_offset (acfg, ji);
3973 emit_code (MonoAotCompile *acfg)
3979 symbol = g_strdup_printf ("methods");
3980 emit_section_change (acfg, ".text", 0);
3981 emit_global (acfg, symbol, TRUE);
3982 emit_alignment (acfg, 8);
3983 emit_label (acfg, symbol);
3986 for (l = acfg->method_order; l != NULL; l = l->next) {
3987 i = GPOINTER_TO_UINT (l->data);
3990 emit_method_code (acfg, acfg->cfgs [i]);
3993 symbol = g_strdup_printf ("methods_end");
3994 emit_section_change (acfg, ".text", 0);
3995 emit_global (acfg, symbol, FALSE);
3996 emit_alignment (acfg, 8);
3997 emit_label (acfg, symbol);
4000 symbol = g_strdup_printf ("method_offsets");
4001 emit_section_change (acfg, ".text", 1);
4002 emit_global (acfg, symbol, FALSE);
4003 emit_alignment (acfg, 8);
4004 emit_label (acfg, symbol);
4007 for (i = 0; i < acfg->nmethods; ++i) {
4008 if (acfg->cfgs [i]) {
4009 symbol = g_strdup_printf (".Lm_%x", i);
4010 emit_symbol_diff (acfg, symbol, "methods", 0);
4013 emit_int32 (acfg, 0xffffffff);
4020 emit_info (MonoAotCompile *acfg)
4026 /* Emit method info */
4027 symbol = g_strdup_printf ("method_info");
4028 emit_section_change (acfg, ".text", 1);
4029 emit_global (acfg, symbol, FALSE);
4030 emit_alignment (acfg, 8);
4031 emit_label (acfg, symbol);
4034 /* To reduce size of generated assembly code */
4035 symbol = g_strdup_printf ("mi");
4036 emit_label (acfg, symbol);
4039 for (l = acfg->method_order; l != NULL; l = l->next) {
4040 i = GPOINTER_TO_UINT (l->data);
4043 emit_method_info (acfg, acfg->cfgs [i]);
4046 symbol = g_strdup_printf ("method_info_offsets");
4047 emit_section_change (acfg, ".text", 1);
4048 emit_global (acfg, symbol, FALSE);
4049 emit_alignment (acfg, 8);
4050 emit_label (acfg, symbol);
4053 for (i = 0; i < acfg->nmethods; ++i) {
4054 if (acfg->cfgs [i]) {
4055 symbol = g_strdup_printf (".Lm_%x_p", i);
4056 emit_symbol_diff (acfg, symbol, "mi", 0);
4059 emit_int32 (acfg, 0);
4065 typedef struct HashEntry {
4066 guint32 key, value, index;
4067 struct HashEntry *next;
4071 * emit_extra_methods:
4073 * Emit methods which are not in the METHOD table, like wrappers.
4076 emit_extra_methods (MonoAotCompile *acfg)
4078 int i, table_size, buf_size;
4081 guint32 *info_offsets;
4084 HashEntry *entry, *new_entry;
4087 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4089 buf_size = acfg->extra_methods->len * 256 + 256;
4090 p = buf = g_malloc (buf_size);
4092 /* Encode method info */
4094 /* So offsets are > 0 */
4097 for (i = 0; i < acfg->extra_methods->len; ++i) {
4098 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4099 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4105 info_offsets [i] = p - buf;
4107 if (method->wrapper_type) {
4110 // FIXME: Optimize disk usage
4111 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
4112 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4113 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
4116 name = mono_method_full_name (cfg->orig_method, TRUE);
4119 encode_value (1, p, &p);
4120 strcpy ((char*)p, name);
4121 p += strlen (name ) + 1;
4124 encode_value (0, p, &p);
4125 encode_method_ref (acfg, method, p, &p);
4128 g_assert ((p - buf) < buf_size);
4131 g_assert ((p - buf) < buf_size);
4133 /* Emit method info */
4134 symbol = g_strdup_printf ("extra_method_info");
4135 emit_section_change (acfg, ".text", 1);
4136 emit_global (acfg, symbol, FALSE);
4137 emit_alignment (acfg, 8);
4138 emit_label (acfg, symbol);
4141 emit_bytes (acfg, buf, p - buf);
4146 * Construct a chained hash table for mapping indexes in extra_method_info to
4149 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4150 table = g_ptr_array_sized_new (table_size);
4151 for (i = 0; i < table_size; ++i)
4152 g_ptr_array_add (table, NULL);
4153 for (i = 0; i < acfg->extra_methods->len; ++i) {
4154 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4155 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4161 key = info_offsets [i];
4162 value = get_method_index (acfg, method);
4164 if (method->wrapper_type) {
4165 hash = g_str_hash (method->name) % table_size;
4168 hash = 0 % table_size;
4171 /* FIXME: Allocate from the mempool */
4172 new_entry = g_new0 (HashEntry, 1);
4173 new_entry->key = key;
4174 new_entry->value = value;
4176 entry = g_ptr_array_index (table, hash);
4177 if (entry == NULL) {
4178 new_entry->index = hash;
4179 g_ptr_array_index (table, hash) = new_entry;
4182 entry = entry->next;
4184 entry->next = new_entry;
4185 new_entry->index = table->len;
4186 g_ptr_array_add (table, new_entry);
4190 /* Emit the table */
4191 symbol = g_strdup_printf ("extra_method_table");
4192 emit_section_change (acfg, ".text", 0);
4193 emit_global (acfg, symbol, FALSE);
4194 emit_alignment (acfg, 8);
4195 emit_label (acfg, symbol);
4198 g_assert (table_size < 65000);
4199 emit_int32 (acfg, table_size);
4200 g_assert (table->len < 65000);
4201 for (i = 0; i < table->len; ++i) {
4202 HashEntry *entry = g_ptr_array_index (table, i);
4204 if (entry == NULL) {
4205 emit_int32 (acfg, 0);
4206 emit_int32 (acfg, 0);
4207 emit_int32 (acfg, 0);
4209 g_assert (entry->key > 0);
4210 emit_int32 (acfg, entry->key);
4211 emit_int32 (acfg, entry->value);
4213 emit_int32 (acfg, entry->next->index);
4215 emit_int32 (acfg, 0);
4220 * Emit a table reverse mapping method indexes to their index in extra_method_info.
4221 * This is used by mono_aot_find_jit_info ().
4223 symbol = g_strdup_printf ("extra_method_info_offsets");
4224 emit_section_change (acfg, ".text", 0);
4225 emit_global (acfg, symbol, FALSE);
4226 emit_alignment (acfg, 8);
4227 emit_label (acfg, symbol);
4230 emit_int32 (acfg, acfg->extra_methods->len);
4231 for (i = 0; i < acfg->extra_methods->len; ++i) {
4232 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4234 emit_int32 (acfg, get_method_index (acfg, method));
4235 emit_int32 (acfg, info_offsets [i]);
4240 emit_method_order (MonoAotCompile *acfg)
4246 symbol = g_strdup_printf ("method_order");
4247 emit_section_change (acfg, ".text", 1);
4248 emit_global (acfg, symbol, FALSE);
4249 emit_alignment (acfg, 8);
4250 emit_label (acfg, symbol);
4253 /* First emit an index table */
4256 for (l = acfg->method_order; l != NULL; l = l->next) {
4257 i = GPOINTER_TO_UINT (l->data);
4259 if (acfg->cfgs [i]) {
4260 if ((index % 1024) == 0) {
4261 emit_int32 (acfg, i);
4269 emit_int32 (acfg, 0xffffff);
4271 /* Then emit the whole method order */
4272 for (l = acfg->method_order; l != NULL; l = l->next) {
4273 i = GPOINTER_TO_UINT (l->data);
4275 if (acfg->cfgs [i]) {
4276 emit_int32 (acfg, i);
4281 symbol = g_strdup_printf ("method_order_end");
4282 emit_section_change (acfg, ".text", 1);
4283 emit_global (acfg, symbol, FALSE);
4284 emit_label (acfg, symbol);
4289 emit_exception_info (MonoAotCompile *acfg)
4294 symbol = g_strdup_printf ("ex_info");
4295 emit_section_change (acfg, ".text", 1);
4296 emit_global (acfg, symbol, FALSE);
4297 emit_alignment (acfg, 8);
4298 emit_label (acfg, symbol);
4301 /* To reduce size of generated assembly */
4302 symbol = g_strdup_printf ("ex");
4303 emit_label (acfg, symbol);
4306 for (i = 0; i < acfg->nmethods; ++i) {
4308 emit_exception_debug_info (acfg, acfg->cfgs [i]);
4311 symbol = g_strdup_printf ("ex_info_offsets");
4312 emit_section_change (acfg, ".text", 1);
4313 emit_global (acfg, symbol, FALSE);
4314 emit_alignment (acfg, 8);
4315 emit_label (acfg, symbol);
4318 for (i = 0; i < acfg->nmethods; ++i) {
4319 if (acfg->cfgs [i]) {
4320 symbol = g_strdup_printf (".Le_%x_p", i);
4321 emit_symbol_diff (acfg, symbol, "ex", 0);
4324 emit_int32 (acfg, 0);
4331 emit_class_info (MonoAotCompile *acfg)
4336 symbol = g_strdup_printf ("class_info");
4337 emit_section_change (acfg, ".text", 1);
4338 emit_global (acfg, symbol, FALSE);
4339 emit_alignment (acfg, 8);
4340 emit_label (acfg, symbol);
4343 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4344 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4346 symbol = g_strdup_printf ("class_info_offsets");
4347 emit_section_change (acfg, ".text", 1);
4348 emit_global (acfg, symbol, FALSE);
4349 emit_alignment (acfg, 8);
4350 emit_label (acfg, symbol);
4353 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4354 symbol = g_strdup_printf (".LK_I_%x", i);
4355 emit_symbol_diff (acfg, symbol, "class_info", 0);
4361 typedef struct ClassNameTableEntry {
4362 guint32 token, index;
4363 struct ClassNameTableEntry *next;
4364 } ClassNameTableEntry;
4367 emit_class_name_table (MonoAotCompile *acfg)
4370 guint32 token, hash;
4375 ClassNameTableEntry *entry, *new_entry;
4378 * Construct a chained hash table for mapping class names to typedef tokens.
4380 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4381 table = g_ptr_array_sized_new (table_size);
4382 for (i = 0; i < table_size; ++i)
4383 g_ptr_array_add (table, NULL);
4384 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4385 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4386 klass = mono_class_get (acfg->image, token);
4387 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4388 hash = g_str_hash (full_name) % table_size;
4391 /* FIXME: Allocate from the mempool */
4392 new_entry = g_new0 (ClassNameTableEntry, 1);
4393 new_entry->token = token;
4395 entry = g_ptr_array_index (table, hash);
4396 if (entry == NULL) {
4397 new_entry->index = hash;
4398 g_ptr_array_index (table, hash) = new_entry;
4401 entry = entry->next;
4403 entry->next = new_entry;
4404 new_entry->index = table->len;
4405 g_ptr_array_add (table, new_entry);
4409 /* Emit the table */
4410 symbol = g_strdup_printf ("class_name_table");
4411 emit_section_change (acfg, ".text", 0);
4412 emit_global (acfg, symbol, FALSE);
4413 emit_alignment (acfg, 8);
4414 emit_label (acfg, symbol);
4417 /* FIXME: Optimize memory usage */
4418 g_assert (table_size < 65000);
4419 emit_int16 (acfg, table_size);
4420 g_assert (table->len < 65000);
4421 for (i = 0; i < table->len; ++i) {
4422 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4424 if (entry == NULL) {
4425 emit_int16 (acfg, 0);
4426 emit_int16 (acfg, 0);
4428 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4430 emit_int16 (acfg, entry->next->index);
4432 emit_int16 (acfg, 0);
4438 emit_image_table (MonoAotCompile *acfg)
4444 * The image table is small but referenced in a lot of places.
4445 * So we emit it at once, and reference its elements by an index.
4448 symbol = g_strdup_printf ("mono_image_table");
4449 emit_section_change (acfg, ".text", 1);
4450 emit_global (acfg, symbol, FALSE);
4451 emit_alignment (acfg, 8);
4452 emit_label (acfg, symbol);
4455 emit_int32 (acfg, acfg->image_table->len);
4456 for (i = 0; i < acfg->image_table->len; i++) {
4457 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4458 MonoAssemblyName *aname = &image->assembly->aname;
4460 /* FIXME: Support multi-module assemblies */
4461 g_assert (image->assembly->image == image);
4463 emit_string (acfg, image->assembly_name);
4464 emit_string (acfg, image->guid);
4465 emit_string (acfg, aname->culture ? aname->culture : "");
4466 emit_string (acfg, (const char*)aname->public_key_token);
4468 emit_alignment (acfg, 8);
4469 emit_int32 (acfg, aname->flags);
4470 emit_int32 (acfg, aname->major);
4471 emit_int32 (acfg, aname->minor);
4472 emit_int32 (acfg, aname->build);
4473 emit_int32 (acfg, aname->revision);
4478 emit_got_info (MonoAotCompile *acfg)
4483 guint32 *got_info_offsets;
4487 * - optimize offsets table.
4488 * - reduce number of exported symbols.
4489 * - emit info for a klass only once.
4490 * - determine when a method uses a GOT slot which is guaranteed to be already
4492 * - clean up and document the code.
4493 * - use String.Empty in class libs.
4496 /* Encode info required to decode shared GOT entries */
4497 buf_size = acfg->shared_patches->len * 64;
4498 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4499 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
4500 for (i = 0; i < acfg->shared_patches->len; ++i) {
4501 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
4503 /* No need to encode the patch type */
4504 got_info_offsets [i] = p - buf;
4505 encode_patch (acfg, ji, p, &p);
4508 g_assert (p - buf <= buf_size);
4510 acfg->stats.got_info_size = p - buf;
4512 /* Emit got_info table */
4513 symbol = g_strdup_printf ("got_info");
4514 emit_section_change (acfg, ".text", 1);
4515 emit_global (acfg, symbol, FALSE);
4516 emit_alignment (acfg, 8);
4517 emit_label (acfg, symbol);
4520 emit_bytes (acfg, buf, p - buf);
4522 /* Emit got_info_offsets table */
4523 symbol = g_strdup_printf ("got_info_offsets");
4524 emit_section_change (acfg, ".text", 1);
4525 emit_global (acfg, symbol, FALSE);
4526 emit_alignment (acfg, 8);
4527 emit_label (acfg, symbol);
4530 for (i = 0; i < acfg->shared_patches->len; ++i)
4531 emit_int32 (acfg, got_info_offsets [i]);
4533 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
4537 emit_got (MonoAotCompile *acfg)
4541 /* Don't make GOT global so accesses to it don't need relocations */
4542 symbol = g_strdup_printf ("got");
4543 emit_section_change (acfg, ".bss", 1);
4544 emit_alignment (acfg, 8);
4545 emit_label (acfg, symbol);
4546 if ((acfg->got_offset + acfg->num_trampoline_got_entries) > 0)
4547 emit_zero_bytes (acfg, (int)((acfg->got_offset + acfg->num_trampoline_got_entries) * sizeof (gpointer)));
4550 symbol = g_strdup_printf ("got_addr");
4551 emit_section_change (acfg, ".data", 1);
4552 emit_global (acfg, symbol, FALSE);
4553 emit_alignment (acfg, 8);
4554 emit_label (acfg, symbol);
4555 emit_pointer (acfg, "got");
4558 symbol = g_strdup_printf ("got_size");
4559 emit_section_change (acfg, ".data", 1);
4560 emit_global (acfg, symbol, FALSE);
4561 emit_alignment (acfg, 8);
4562 emit_label (acfg, symbol);
4563 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4568 emit_globals (MonoAotCompile *acfg)
4572 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4574 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4576 opts_str = g_strdup_printf ("%d", acfg->opts);
4577 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4580 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4582 if (acfg->aot_opts.bind_to_runtime_version)
4583 emit_string_symbol (acfg, "mono_runtime_version", FULL_VERSION);
4585 emit_string_symbol (acfg, "mono_runtime_version", "");
4588 * Some platforms like the iphone have no working dlsym (). To work around this,
4589 * we create an ELF ctor function which will be invoked by dlopen, and which
4590 * will call a function in the AOT loader to register the symbols used by the
4592 * When static linking, we emit a global which will point to the symbol table.
4594 if (acfg->aot_opts.no_dlsym) {
4598 if (acfg->aot_opts.static_link)
4599 /* Emit a string holding the assembly name */
4600 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4602 /* Emit the names */
4603 for (i = 0; i < acfg->globals->len; ++i) {
4604 char *name = g_ptr_array_index (acfg->globals, i);
4606 symbol = g_strdup_printf ("name_%d", i);
4607 emit_section_change (acfg, ".text", 1);
4608 emit_label (acfg, symbol);
4609 emit_string (acfg, name);
4613 /* Emit the globals table */
4614 symbol = g_strdup_printf ("globals");
4615 emit_section_change (acfg, ".data", 0);
4616 /* This is not a global, since it is accessed by the init function */
4617 emit_alignment (acfg, 8);
4618 emit_label (acfg, symbol);
4620 for (i = 0; i < acfg->globals->len; ++i) {
4621 char *name = g_ptr_array_index (acfg->globals, i);
4623 symbol = g_strdup_printf ("name_%d", i);
4624 emit_pointer (acfg, symbol);
4627 symbol = g_strdup_printf ("%s", name);
4628 emit_pointer (acfg, symbol);
4631 /* Null terminate the table */
4632 emit_pointer (acfg, NULL);
4633 emit_pointer (acfg, NULL);
4635 if (acfg->aot_opts.static_link) {
4639 * Emit a global symbol which can be passed by an embedding app to
4640 * mono_aot_register_module ().
4642 #if defined(__MACH__)
4643 symbol = g_strdup_printf ("_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4645 symbol = g_strdup_printf ("mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4648 /* Get rid of characters which cannot occur in symbols */
4650 for (p = symbol; *p; ++p) {
4651 if (!(isalnum (*p) || *p == '_'))
4654 acfg->static_linking_symbol = g_strdup (symbol);
4655 emit_global_inner (acfg, symbol, FALSE);
4656 emit_alignment (acfg, 8);
4657 emit_label (acfg, symbol);
4658 emit_pointer (acfg, "globals");
4660 symbol = g_strdup_printf ("init_%s", acfg->image->assembly->aname.name);
4661 emit_section_change (acfg, ".text", 1);
4662 emit_alignment (acfg, 8);
4663 emit_label (acfg, symbol);
4664 #ifdef USE_BIN_WRITER
4665 g_assert_not_reached ();
4668 fprintf (acfg->fp, "leaq globals(%%rip), %%rdi\n");
4669 fprintf (acfg->fp, "call mono_aot_register_globals@PLT\n");
4670 fprintf (acfg->fp, "ret\n");
4671 fprintf (acfg->fp, ".section .ctors,\"aw\",@progbits\n");
4672 emit_alignment (acfg, 8);
4673 emit_pointer (acfg, symbol);
4674 #elif defined(__arm__) && defined(__MACH__)
4676 fprintf (acfg->fp, ".text\n");
4677 fprintf (acfg->fp, ".align 3\n");
4679 fprintf (acfg->fp, "ldr r0, .L5\n");
4680 fprintf (acfg->fp, ".LPIC0:\n");
4681 fprintf (acfg->fp, "add r0, pc, r0\n");
4682 fprintf (acfg->fp, "ldr r0, [r0]\n");
4683 fprintf (acfg->fp, "b _mono_aot_register_globals@PLT\n");
4684 fprintf (acfg->fp, ".align 2\n");
4686 fprintf (acfg->fp, ".L5:\n");
4687 fprintf (acfg->fp, ".long globals_ptr-(.LPIC0+8)\n");
4689 fprintf (acfg->fp, ".data\n");
4690 fprintf (acfg->fp, ".align 2\n");
4691 fprintf (acfg->fp, "globals_ptr:\n");
4692 fprintf (acfg->fp, ".long globals\n");
4694 fprintf (acfg->fp, ".mod_init_func\n");
4695 fprintf (acfg->fp, ".align 2\n");
4696 fprintf (acfg->fp, ".long %s@target1\n", symbol);
4698 #elif defined(__arm__)
4700 * Taken from gcc generated code for:
4702 * void foo () { bar (&i); }
4703 * gcc --shared -fPIC -O2
4705 fprintf (acfg->fp, "ldr r3, .L5\n");
4706 fprintf (acfg->fp, "ldr r0, .L5+4\n");
4707 fprintf (acfg->fp, ".LPIC0:\n");
4708 fprintf (acfg->fp, "add r3, pc, r3\n");
4709 fprintf (acfg->fp, "add r0, r3, r0\n");
4710 fprintf (acfg->fp, "b mono_aot_register_globals(PLT)\n");
4712 fprintf (acfg->fp, ".L5:\n");
4713 fprintf (acfg->fp, ".word _GLOBAL_OFFSET_TABLE_-(.LPIC0+8)\n");
4714 fprintf (acfg->fp, ".word globals(GOTOFF)\n");
4716 fprintf (acfg->fp, ".section .init_array,\"aw\",%%init_array\n");
4717 fprintf (acfg->fp, ".align 2\n");
4718 fprintf (acfg->fp, ".word %s(target1)\n", symbol);
4720 g_assert_not_reached ();
4729 acfg_free (MonoAotCompile *acfg)
4733 for (i = 0; i < acfg->nmethods; ++i)
4735 g_free (acfg->cfgs [i]);
4736 g_free (acfg->cfgs);
4737 g_free (acfg->static_linking_symbol);
4738 g_ptr_array_free (acfg->methods, TRUE);
4739 g_ptr_array_free (acfg->shared_patches, TRUE);
4740 g_ptr_array_free (acfg->image_table, TRUE);
4741 g_ptr_array_free (acfg->globals, TRUE);
4742 g_hash_table_destroy (acfg->method_indexes);
4743 g_hash_table_destroy (acfg->plt_offset_to_patch);
4744 g_hash_table_destroy (acfg->patch_to_plt_offset);
4745 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
4746 g_hash_table_destroy (acfg->method_to_cfg);
4747 g_hash_table_destroy (acfg->token_info_hash);
4748 g_hash_table_destroy (acfg->image_hash);
4749 mono_mempool_destroy (acfg->mempool);
4754 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4756 MonoImage *image = ass->image;
4759 MonoAotCompile *acfg;
4763 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4765 acfg = g_new0 (MonoAotCompile, 1);
4766 acfg->methods = g_ptr_array_new ();
4767 acfg->method_indexes = g_hash_table_new (NULL, NULL);
4768 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4769 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4770 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4771 acfg->shared_patches = g_ptr_array_new ();
4772 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4773 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4774 acfg->image_hash = g_hash_table_new (NULL, NULL);
4775 acfg->image_table = g_ptr_array_new ();
4776 acfg->globals = g_ptr_array_new ();
4777 acfg->image = image;
4779 acfg->mempool = mono_mempool_new ();
4780 acfg->extra_methods = g_ptr_array_new ();
4782 mono_aot_parse_options (aot_options, &acfg->aot_opts);
4784 load_profile_files (acfg);
4788 acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 10240 : 0;
4790 acfg->method_index = 1;
4792 /* Collect methods */
4793 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4795 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4797 method = mono_get_method (acfg->image, token, NULL);
4799 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4800 /* Compile the wrapper instead */
4801 /* We do this here instead of add_wrappers () because it is easy to do it here */
4802 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4806 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4807 add_method_with_index (acfg, method, i);
4808 acfg->method_index ++;
4811 add_generic_instances (acfg);
4813 if (acfg->aot_opts.full_aot)
4814 add_wrappers (acfg);
4816 acfg->cfgs_size = acfg->methods->len + 32;
4817 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
4819 /* PLT offset 0 is reserved for the PLT trampoline */
4820 acfg->plt_offset = 1;
4822 /* Compile methods */
4824 for (i = 0; i < acfg->methods->len; ++i) {
4825 /* This can new methods to acfg->methods */
4826 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4830 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
4834 alloc_got_slots (acfg);
4840 emit_extra_methods (acfg);
4842 emit_method_order (acfg);
4844 emit_trampolines (acfg);
4846 emit_class_name_table (acfg);
4848 emit_got_info (acfg);
4850 emit_exception_info (acfg);
4852 emit_class_info (acfg);
4856 emit_image_table (acfg);
4860 emit_globals (acfg);
4862 symbol = g_strdup_printf ("mem_end");
4863 emit_section_change (acfg, ".text", 1);
4864 emit_global (acfg, symbol, FALSE);
4865 emit_alignment (acfg, 8);
4866 emit_label (acfg, symbol);
4871 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
4873 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)));
4876 res = emit_writeout (acfg);
4882 acfg->stats.link_time = TV_ELAPSED (atv, btv);
4884 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);
4885 if (acfg->stats.genericcount)
4886 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4887 if (acfg->stats.abscount)
4888 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4889 if (acfg->stats.wrappercount)
4890 printf ("%d methods contain wrapper references (%d%%)\n", acfg->stats.wrappercount, acfg->stats.mcount ? (acfg->stats.wrappercount * 100) / acfg->stats.mcount : 100);
4891 if (acfg->stats.lmfcount)
4892 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4893 if (acfg->stats.ocount)
4894 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4895 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);
4896 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4897 printf ("JIT time: %d ms, Generation time: %d ms, Assembly+Link time: %d ms.\n", acfg->stats.jit_time / 1000, acfg->stats.gen_time / 1000, acfg->stats.link_time / 1000);
4899 printf ("GOT slot distribution:\n");
4900 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4901 if (acfg->stats.got_slot_types [i])
4902 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4914 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)