2 * aot.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
11 /* Remaining AOT-only work:
12 * - reduce the length of the wrapper names.
13 * - aot IMT tables, so we don't have two kinds of aot code.
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
23 * - every shared method has a MonoGenericJitInfo structure which is only really
24 * used for handling catch clauses with open types, not a very common use case.
28 #include <sys/types.h>
35 #ifndef PLATFORM_WIN32
44 #include <limits.h> /* for PAGESIZE */
49 #include <mono/metadata/tabledefs.h>
50 #include <mono/metadata/class.h>
51 #include <mono/metadata/object.h>
52 #include <mono/metadata/tokentype.h>
53 #include <mono/metadata/appdomain.h>
54 #include <mono/metadata/debug-helpers.h>
55 #include <mono/metadata/assembly.h>
56 #include <mono/metadata/metadata-internals.h>
57 #include <mono/metadata/marshal.h>
58 #include <mono/metadata/gc-internal.h>
59 #include <mono/metadata/method-builder.h>
60 #include <mono/metadata/monitor.h>
61 #include <mono/metadata/mempool-internals.h>
62 #include <mono/metadata/mono-endian.h>
63 #include <mono/utils/mono-logger.h>
64 #include <mono/utils/mono-compiler.h>
65 #include <mono/utils/mono-time.h>
67 #ifndef PLATFORM_WIN32
68 #include <mono/utils/freebsd-elf32.h>
69 #include <mono/utils/freebsd-elf64.h>
72 #include <mono/utils/freebsd-dwarf.h>
78 #define TV_DECLARE(name) gint64 name
79 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
80 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
83 #define SHARED_EXT ".dll"
84 #elif defined(__ppc__) && defined(__MACH__)
85 #define SHARED_EXT ".dylib"
87 #define SHARED_EXT ".so"
90 #if defined(sparc) || defined(__ppc__) || defined(__powerpc__) || defined(__MACH__)
91 #define AS_STRING_DIRECTIVE ".asciz"
94 #define AS_STRING_DIRECTIVE ".string"
99 // .byte generates 1 byte per expression.
100 // .short generates 2 bytes per expression.
101 // .long generates 4 bytes per expression.
102 // .quad generates 8 bytes per expression.
104 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
105 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
106 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
108 typedef struct MonoAotOptions {
111 gboolean write_symbols;
112 gboolean metadata_only;
113 gboolean bind_to_runtime_version;
116 gboolean static_link;
122 typedef struct MonoAotStats {
123 int ccount, mcount, lmfcount, abscount, wrappercount, gcount, ocount, genericcount;
124 int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
125 int methods_without_got_slots, direct_calls, all_calls;
127 int got_slot_types [MONO_PATCH_INFO_NONE];
128 int jit_time, gen_time, link_time;
131 #if defined(__x86_64__) && !defined(PLATFORM_WIN32)
132 #define USE_ELF_WRITER 1
133 #define USE_ELF_RELA 1
136 #if defined(__i386__) && !defined(PLATFORM_WIN32)
137 #define USE_ELF_WRITER 1
140 #if defined(__arm__) && !defined(__MACH__)
141 #define USE_ELF_WRITER 1
144 #if defined(__mips__)
145 #define USE_ELF_WRITER 1
148 #if defined(USE_ELF_WRITER)
149 #define USE_BIN_WRITER 1
152 #ifdef USE_BIN_WRITER
154 typedef struct _BinSymbol BinSymbol;
155 typedef struct _BinReloc BinReloc;
156 typedef struct _BinSection BinSection;
168 typedef struct MonoAotCompile {
171 GHashTable *method_indexes;
174 GHashTable *patch_to_plt_offset;
175 GHashTable *plt_offset_to_patch;
176 GHashTable *patch_to_shared_got_offset;
177 GPtrArray *shared_patches;
178 GHashTable *image_hash;
179 GHashTable *method_to_cfg;
180 GHashTable *token_info_hash;
181 GPtrArray *extra_methods;
182 GPtrArray *image_table;
185 guint32 *plt_got_info_offsets;
186 /* Number of trampolines emitted into the AOT file */
187 guint32 num_aot_trampolines;
188 guint32 got_offset, plt_offset, plt_got_offset_base;
189 /* Number of GOT entries reserved for trampolines */
190 guint32 num_trampoline_got_entries;
191 guint32 trampoline_got_offset_base;
192 MonoAotOptions aot_opts;
195 MonoMemPool *mempool;
198 char *static_linking_symbol;
199 CRITICAL_SECTION mutex;
200 gboolean use_bin_writer;
202 #ifdef USE_BIN_WRITER
204 BinSection *sections;
205 BinSection *cur_section;
206 BinReloc *relocations;
213 int mode; /* emit mode */
214 int col_count; /* bytes emitted per .byte line */
216 GHashTable *class_to_die;
217 int fde_index, tdie_index;
220 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
221 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
223 #ifdef HAVE_ARRAY_ELEM_INIT
224 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
225 #define MSGSTRFIELD1(line) str##line
226 static const struct msgstr_t {
227 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
228 #include "patch-info.h"
231 #define PATCH_INFO(a,b) b,
232 #include "patch-info.h"
235 static const gint16 opidx [] = {
236 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
237 #include "patch-info.h"
242 get_patch_name (int info)
244 return (const char*)&opstr + opidx [info];
248 #define PATCH_INFO(a,b) b,
249 static const char* const
250 patch_types [MONO_PATCH_INFO_NUM + 1] = {
251 #include "patch-info.h"
256 get_patch_name (int info)
258 return patch_types [info];
264 emit_global (MonoAotCompile *acfg, const char *name, gboolean func);
267 is_got_patch (MonoJumpInfoType patch_type)
272 static G_GNUC_UNUSED int
273 ilog2(register int value)
276 while (value & ~0xf) count += 4, value >>= 4;
277 while (value) count++, value >>= 1;
281 #ifdef USE_BIN_WRITER
283 typedef struct _BinLabel BinLabel;
294 BinSection *val2_section;
307 gboolean is_function;
326 bin_writer_emit_start (MonoAotCompile *acfg)
328 acfg->labels = g_hash_table_new (g_str_hash, g_str_equal);
332 bin_writer_emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
336 if (acfg->cur_section && acfg->cur_section->subsection == subsection_index
337 && strcmp (acfg->cur_section->name, section_name) == 0)
339 for (section = acfg->sections; section; section = section->next) {
340 if (section->subsection == subsection_index && strcmp (section->name, section_name) == 0) {
341 acfg->cur_section = section;
346 section = g_new0 (BinSection, 1);
347 section->name = g_strdup (section_name);
348 section->subsection = subsection_index;
349 section->next = acfg->sections;
350 acfg->sections = section;
351 acfg->cur_section = section;
356 bin_writer_emit_symbol_inner (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean is_global, gboolean func)
358 BinSymbol *symbol = g_new0 (BinSymbol, 1);
359 symbol->name = g_strdup (name);
361 symbol->end_label = g_strdup (end_label);
362 symbol->is_function = func;
363 symbol->is_global = is_global;
364 symbol->section = acfg->cur_section;
365 /* FIXME: we align after this call... */
366 symbol->offset = symbol->section->cur_offset;
367 symbol->next = acfg->symbols;
368 acfg->symbols = symbol;
372 bin_writer_emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
374 bin_writer_emit_symbol_inner (acfg, name, NULL, TRUE, func);
378 bin_writer_emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
380 bin_writer_emit_symbol_inner (acfg, name, end_label, FALSE, func);
384 bin_writer_emit_label (MonoAotCompile *acfg, const char *name)
386 BinLabel *label = g_new0 (BinLabel, 1);
387 label->name = g_strdup (name);
388 label->section = acfg->cur_section;
389 label->offset = acfg->cur_section->cur_offset;
390 g_hash_table_insert (acfg->labels, label->name, label);
394 bin_writer_emit_ensure_buffer (BinSection *section, int size)
396 int new_offset = section->cur_offset + size;
397 if (new_offset >= section->data_len) {
398 int new_size = section->data_len? section->data_len * 2: 256;
400 while (new_size <= new_offset)
402 data = g_malloc0 (new_size);
403 memcpy (data, section->data, section->data_len);
404 g_free (section->data);
405 section->data = data;
406 section->data_len = new_size;
411 bin_writer_emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
413 bin_writer_emit_ensure_buffer (acfg->cur_section, size);
414 memcpy (acfg->cur_section->data + acfg->cur_section->cur_offset, buf, size);
415 acfg->cur_section->cur_offset += size;
419 bin_writer_emit_string (MonoAotCompile *acfg, const char *value)
421 int size = strlen (value) + 1;
422 bin_writer_emit_bytes (acfg, (const guint8*)value, size);
426 bin_writer_emit_line (MonoAotCompile *acfg)
428 /* Nothing to do in binary writer */
432 bin_writer_emit_alignment (MonoAotCompile *acfg, int size)
434 int offset = acfg->cur_section->cur_offset;
436 offset += (size - 1);
437 offset &= ~(size - 1);
438 add = offset - acfg->cur_section->cur_offset;
440 bin_writer_emit_ensure_buffer (acfg->cur_section, add);
441 acfg->cur_section->cur_offset += add;
446 bin_writer_emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
452 g_assert_not_reached ();
453 reloc = g_new0 (BinReloc, 1);
454 reloc->val1 = g_strdup (target);
455 reloc->section = acfg->cur_section;
456 reloc->section_offset = acfg->cur_section->cur_offset;
457 reloc->next = acfg->relocations;
458 acfg->relocations = reloc;
459 if (strcmp (reloc->section->name, ".data") == 0) {
461 g_print ("reloc: %s at %d\n", target, acfg->cur_section->cur_offset);
463 acfg->cur_section->cur_offset += sizeof (gpointer);
467 bin_writer_emit_pointer (MonoAotCompile *acfg, const char *target)
469 bin_writer_emit_alignment (acfg, sizeof (gpointer));
470 bin_writer_emit_pointer_unaligned (acfg, target);
474 bin_writer_emit_int16 (MonoAotCompile *acfg, int value)
477 bin_writer_emit_ensure_buffer (acfg->cur_section, 2);
478 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
479 acfg->cur_section->cur_offset += 2;
480 /* FIXME: little endian */
482 data [1] = value >> 8;
486 bin_writer_emit_int32 (MonoAotCompile *acfg, int value)
489 bin_writer_emit_ensure_buffer (acfg->cur_section, 4);
490 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
491 acfg->cur_section->cur_offset += 4;
492 /* FIXME: little endian */
494 data [1] = value >> 8;
495 data [2] = value >> 16;
496 data [3] = value >> 24;
500 create_reloc (MonoAotCompile *acfg, const char *end, const char* start, int offset)
503 reloc = mono_mempool_alloc0 (acfg->mempool, sizeof (BinReloc));
504 reloc->val1 = mono_mempool_strdup (acfg->mempool, end);
505 if (strcmp (start, ".") == 0) {
506 reloc->val2_section = acfg->cur_section;
507 reloc->val2_offset = acfg->cur_section->cur_offset;
509 reloc->val2 = mono_mempool_strdup (acfg->mempool, start);
511 reloc->offset = offset;
512 reloc->section = acfg->cur_section;
513 reloc->section_offset = acfg->cur_section->cur_offset;
514 reloc->next = acfg->relocations;
515 acfg->relocations = reloc;
520 bin_writer_emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
522 create_reloc (acfg, end, start, offset);
523 acfg->cur_section->cur_offset += 4;
524 /*if (strcmp (reloc->section->name, ".data") == 0) {
526 g_print ("reloc: %s - %s + %d at %d\n", end, start, offset, acfg->cur_section->cur_offset - 4);
531 * Emit a relocation entry of type RELOC_TYPE against symbol SYMBOL at the current PC.
534 static G_GNUC_UNUSED void
535 bin_writer_emit_reloc (MonoAotCompile *acfg, int reloc_type, const char *symbol, int addend)
537 BinReloc *reloc = create_reloc (acfg, symbol, ".", addend);
538 reloc->reloc_type = reloc_type;
542 bin_writer_emit_zero_bytes (MonoAotCompile *acfg, int num)
544 bin_writer_emit_ensure_buffer (acfg->cur_section, num);
545 acfg->cur_section->cur_offset += num;
548 #ifdef USE_ELF_WRITER
571 /* Relocation types */
572 #define R_ARM_CALL 28
573 #define R_ARM_ALU_PC_G0_NC 59
575 #if SIZEOF_VOID_P == 4
577 typedef Elf32_Ehdr ElfHeader;
578 typedef Elf32_Shdr ElfSectHeader;
579 typedef Elf32_Phdr ElfProgHeader;
580 typedef Elf32_Sym ElfSymbol;
581 typedef Elf32_Rel ElfReloc;
582 typedef Elf32_Rela ElfRelocA;
583 typedef Elf32_Dyn ElfDynamic;
587 typedef Elf64_Ehdr ElfHeader;
588 typedef Elf64_Shdr ElfSectHeader;
589 typedef Elf64_Phdr ElfProgHeader;
590 typedef Elf64_Sym ElfSymbol;
591 typedef Elf64_Rel ElfReloc;
592 typedef Elf64_Rela ElfRelocA;
593 typedef Elf64_Dyn ElfDynamic;
605 static SectInfo section_info [] = {
607 {".hash", SHT_HASH, 4, 2, SIZEOF_VOID_P},
608 {".dynsym", SHT_DYNSYM, sizeof (ElfSymbol), 2, SIZEOF_VOID_P},
609 {".dynstr", SHT_STRTAB, 0, 2, 1},
610 {".rel.dyn", SHT_REL, sizeof (ElfReloc), 2, SIZEOF_VOID_P},
611 {".rela.dyn", SHT_RELA, sizeof (ElfRelocA), 2, SIZEOF_VOID_P},
612 {".text", SHT_PROGBITS, 0, 6, 4096},
613 {".dynamic", SHT_DYNAMIC, sizeof (ElfDynamic), 3, SIZEOF_VOID_P},
614 {".got.plt", SHT_PROGBITS, SIZEOF_VOID_P, 3, SIZEOF_VOID_P},
615 {".data", SHT_PROGBITS, 0, 3, 8},
616 {".bss", SHT_NOBITS, 0, 3, 8},
617 {".debug_frame", SHT_PROGBITS, 0, 0, 8},
618 {".debug_info", SHT_PROGBITS, 0, 0, 1},
619 {".debug_abbrev", SHT_PROGBITS, 0, 0, 1},
620 {".shstrtab", SHT_STRTAB, 0, 0, 1},
621 {".symtab", SHT_SYMTAB, sizeof (ElfSymbol), 0, SIZEOF_VOID_P},
622 {".strtab", SHT_STRTAB, 0, 0, 1}
631 str_table_add (ElfStrTable *table, const char* value)
635 table->data = g_string_new_len ("", 1);
636 table->hash = g_hash_table_new (g_str_hash, g_str_equal);
638 idx = GPOINTER_TO_UINT (g_hash_table_lookup (table->hash, value));
641 idx = table->data->len;
642 g_string_append (table->data, value);
643 g_string_append_c (table->data, 0);
644 g_hash_table_insert (table->hash, (void*)value, GUINT_TO_POINTER (idx));
649 append_subsection (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection *sect, BinSection *add)
651 int offset = sect->cur_offset;
652 /*offset += (sheaders [sect->shidx].sh_addralign - 1);
653 offset &= ~(sheaders [sect->shidx].sh_addralign - 1);*/
656 bin_writer_emit_ensure_buffer (sect, offset);
657 g_print ("section %s aligned to %d from %d\n", sect->name, offset, sect->cur_offset);
658 sect->cur_offset = offset;
660 bin_writer_emit_ensure_buffer (sect, add->cur_offset);
661 memcpy (sect->data + sect->cur_offset, add->data, add->cur_offset);
663 sect->cur_offset += add->cur_offset;
664 add->cur_offset = offset; /* it becomes the offset in the parent section */
665 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);
670 /* merge the subsections */
672 collect_sections (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection **out, int num)
674 int i, j, maxs, num_sections;
679 for (sect = acfg->sections; sect; sect = sect->next) {
680 if (sect->subsection == 0) {
681 out [num_sections++] = sect;
682 g_assert (num_sections < num);
684 maxs = MAX (maxs, sect->subsection);
686 for (i = 0; i < num_sections; i++) {
687 for (j = 1; j <= maxs; ++j) {
688 for (sect = acfg->sections; sect; sect = sect->next) {
689 if (sect->subsection == j && strcmp (out [i]->name, sect->name) == 0) {
690 append_subsection (acfg, sheaders, out [i], sect);
699 elf_hash (const unsigned char *name)
701 unsigned long h = 0, g;
703 h = (h << 4) + *name++;
704 if ((g = h & 0xf0000000))
711 #define NUM_BUCKETS 17
714 build_hash (MonoAotCompile *acfg, int num_sections, ElfStrTable *dynstr)
717 int num_symbols = 1 + num_sections + 3;
720 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
721 if (!symbol->is_global)
724 str_table_add (dynstr, symbol->name);
725 /*g_print ("adding sym: %s\n", symbol->name);*/
727 str_table_add (dynstr, "__bss_start");
728 str_table_add (dynstr, "_edata");
729 str_table_add (dynstr, "_end");
731 data = g_new0 (int, num_symbols + 2 + NUM_BUCKETS);
732 data [0] = NUM_BUCKETS;
733 data [1] = num_symbols;
739 get_label_addr (MonoAotCompile *acfg, const char *name)
746 lab = g_hash_table_lookup (acfg->labels, name);
748 g_error ("Undefined label: '%s'.\n", name);
749 section = lab->section;
750 offset = lab->offset;
751 if (section->parent) {
752 value = section->parent->virt_offset + section->cur_offset + offset;
754 value = section->virt_offset + offset;
760 collect_syms (MonoAotCompile *acfg, int *hash, ElfStrTable *strtab, ElfSectHeader *sheaders, int *num_syms)
771 symbols = g_new0 (ElfSymbol, hash [1]);
774 for (symbol = acfg->symbols; symbol; symbol = symbol->next)
777 symbols = g_new0 (ElfSymbol, i + SECT_NUM + 10); /* FIXME */
780 /* the first symbol is undef, all zeroes */
784 for (j = 1; j < SECT_NUM; ++j) {
785 symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
786 symbols [i].st_shndx = j;
787 symbols [i].st_value = sheaders [j].sh_addr;
791 for (section = acfg->sections; section; section = section->next) {
794 symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
795 if (strcmp (section->name, ".text") == 0) {
796 symbols [i].st_shndx = SECT_TEXT;
797 section->shidx = SECT_TEXT;
798 section->file_offset = 4096;
799 symbols [i].st_value = section->virt_offset;
800 } else if (strcmp (section->name, ".data") == 0) {
801 symbols [i].st_shndx = SECT_DATA;
802 section->shidx = SECT_DATA;
803 section->file_offset = 4096 + 28; /* FIXME */
804 symbols [i].st_value = section->virt_offset;
805 } else if (strcmp (section->name, ".bss") == 0) {
806 symbols [i].st_shndx = SECT_BSS;
807 section->shidx = SECT_BSS;
808 section->file_offset = 4096 + 28 + 8; /* FIXME */
809 symbols [i].st_value = section->virt_offset;
814 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
817 if (!symbol->is_global && hash)
819 symbols [i].st_info = ELF32_ST_INFO (symbol->is_global ? STB_GLOBAL : STB_LOCAL, symbol->is_function? STT_FUNC : STT_OBJECT);
820 symbols [i].st_name = str_table_add (strtab, symbol->name);
821 /*g_print ("sym name %s tabled to %d\n", symbol->name, symbols [i].st_name);*/
822 section = symbol->section;
823 symbols [i].st_shndx = section->parent? section->parent->shidx: section->shidx;
824 lab = g_hash_table_lookup (acfg->labels, symbol->name);
825 offset = lab->offset;
826 if (section->parent) {
827 symbols [i].st_value = section->parent->virt_offset + section->cur_offset + offset;
829 symbols [i].st_value = section->virt_offset + offset;
832 if (symbol->end_label) {
833 BinLabel *elab = g_hash_table_lookup (acfg->labels, symbol->end_label);
835 symbols [i].st_size = elab->offset - lab->offset;
839 /* add special symbols */
840 symbols [i].st_name = str_table_add (strtab, "__bss_start");
841 symbols [i].st_shndx = 0xfff1;
842 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
844 symbols [i].st_name = str_table_add (strtab, "_edata");
845 symbols [i].st_shndx = 0xfff1;
846 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
848 symbols [i].st_name = str_table_add (strtab, "_end");
849 symbols [i].st_shndx = 0xfff1;
850 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
856 /* add to hash table */
859 chain = hash + 2 + hash [0];
860 for (i = 0; i < hash [1]; ++i) {
862 /*g_print ("checking %d '%s' (sym %d)\n", symbols [i].st_name, strtab->data->str + symbols [i].st_name, i);*/
863 if (!symbols [i].st_name)
865 hashc = elf_hash ((guint8*)strtab->data->str + symbols [i].st_name);
866 slot = hashc % hash [0];
867 /*g_print ("hashing '%s' at slot %d (sym %d)\n", strtab->data->str + symbols [i].st_name, slot, i);*/
869 chain [i] = bucket [slot];
880 reloc_symbols (MonoAotCompile *acfg, ElfSymbol *symbols, ElfSectHeader *sheaders, ElfStrTable *strtab, gboolean dynamic)
888 for (section = acfg->sections; section; section = section->next) {
891 symbols [i].st_value = sheaders [section->shidx].sh_addr;
895 for (i = 1; i < SECT_NUM; ++i) {
896 symbols [i].st_value = sheaders [i].sh_addr;
899 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
902 if (dynamic && !symbol->is_global)
904 section = symbol->section;
905 lab = g_hash_table_lookup (acfg->labels, symbol->name);
906 offset = lab->offset;
907 if (section->parent) {
908 symbols [i].st_value = sheaders [section->parent->shidx].sh_addr + section->cur_offset + offset;
910 symbols [i].st_value = sheaders [section->shidx].sh_addr + offset;
915 symbols [i].st_value = sheaders [SECT_BSS].sh_addr;
918 symbols [i].st_value = sheaders [SECT_DATA].sh_addr + sheaders [SECT_DATA].sh_size;
921 symbols [i].st_value = sheaders [SECT_BSS].sh_addr + sheaders [SECT_BSS].sh_size;
926 resolve_reloc (MonoAotCompile *acfg, BinReloc *reloc, guint8 **out_data, gsize *out_vaddr, gsize *out_start_val, gsize *out_end_val)
929 gssize end_val, start_val;
932 end_val = get_label_addr (acfg, reloc->val1);
934 start_val = get_label_addr (acfg, reloc->val2);
935 } else if (reloc->val2_section) {
936 start_val = reloc->val2_offset;
937 if (reloc->val2_section->parent)
938 start_val += reloc->val2_section->parent->virt_offset + reloc->val2_section->cur_offset;
940 start_val += reloc->val2_section->virt_offset;
944 end_val = end_val - start_val + reloc->offset;
945 if (reloc->section->parent) {
946 data = reloc->section->parent->data;
947 data += reloc->section->cur_offset;
948 data += reloc->section_offset;
949 vaddr = reloc->section->parent->virt_offset;
950 vaddr += reloc->section->cur_offset;
951 vaddr += reloc->section_offset;
953 data = reloc->section->data;
954 data += reloc->section_offset;
955 vaddr = reloc->section->virt_offset;
956 vaddr += reloc->section_offset;
959 *out_start_val = start_val;
960 *out_end_val = end_val;
968 resolve_relocations (MonoAotCompile *acfg)
972 gsize end_val, start_val;
977 rr = g_new0 (ElfRelocA, acfg->num_relocs);
980 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
981 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
982 /* FIXME: little endian */
984 data [1] = end_val >> 8;
985 data [2] = end_val >> 16;
986 data [3] = end_val >> 24;
988 if (start_val == 0 && reloc->val1 [0] != '.') {
989 rr [i].r_offset = vaddr;
990 rr [i].r_info = R_X86_64_RELATIVE;
991 rr [i].r_addend = end_val;
993 g_assert (i <= acfg->num_relocs);
999 #else /* USE_ELF_RELA */
1002 do_reloc (MonoAotCompile *acfg, BinReloc *reloc, guint8 *data, gssize addr)
1006 * We use the official ARM relocation types, but implement only the stuff actually
1007 * needed by the code we generate.
1009 switch (reloc->reloc_type) {
1011 guint32 *code = (guint32*)(gpointer)data;
1012 guint32 ins = *code;
1016 g_assert (data [3] == 0xeb);
1017 if (diff >= 0 && diff <= 33554431) {
1019 ins = (ins & 0xff000000) | diff;
1021 } else if (diff <= 0 && diff >= -33554432) {
1023 ins = (ins & 0xff000000) | (diff & ~0xff000000);
1026 g_assert_not_reached ();
1030 case R_ARM_ALU_PC_G0_NC: {
1031 /* Generated by emit_plt () */
1032 guint8 *code = data;
1035 g_assert (val <= 0xffff);
1036 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
1037 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, (val & 0xFF00) >> 8, 24);
1038 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, val & 0xFF);
1042 g_assert_not_reached ();
1045 g_assert_not_reached ();
1050 resolve_relocations (MonoAotCompile *acfg)
1054 gsize end_val, start_val;
1059 rr = g_new0 (ElfReloc, acfg->num_relocs);
1062 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
1063 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
1064 /* FIXME: little endian */
1065 if (reloc->reloc_type) {
1066 /* Must be static */
1067 g_assert (start_val > 0);
1068 do_reloc (acfg, reloc, data, end_val);
1071 data [1] = end_val >> 8;
1072 data [2] = end_val >> 16;
1073 data [3] = end_val >> 24;
1076 if (start_val == 0 && reloc->val1 [0] != '.') {
1077 rr [i].r_offset = vaddr;
1078 rr [i].r_info = R_386_RELATIVE;
1080 g_assert (i <= acfg->num_relocs);
1086 #endif /* USE_ELF_RELA */
1089 bin_writer_emit_writeout (MonoAotCompile *acfg)
1091 char *outfile_name, *tmp_outfile_name;
1094 ElfProgHeader progh [3];
1095 ElfSectHeader secth [SECT_NUM];
1101 ElfStrTable str_table = {NULL, NULL};
1102 ElfStrTable sh_str_table = {NULL, NULL};
1103 ElfStrTable dyn_str_table = {NULL, NULL};
1104 BinSection* all_sections [32];
1105 BinSection* sections [SECT_NUM];
1108 ElfDynamic dynamic [14];
1110 int i, num_sections, file_offset, virt_offset, size, num_symtab;
1113 g_assert (!acfg->aot_opts.asm_only);
1115 if (acfg->aot_opts.outfile)
1116 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1118 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1120 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1122 unlink (tmp_outfile_name);
1123 file = fopen (tmp_outfile_name, "w");
1126 /* Section headers */
1127 memset (§h, 0, sizeof (secth));
1128 memset (&dynamic, 0, sizeof (dynamic));
1129 memset (&header, 0, sizeof (header));
1131 for (i = 1; i < SECT_NUM; ++i) {
1132 secth [i].sh_name = str_table_add (&sh_str_table, section_info [i].name);
1133 secth [i].sh_type = section_info [i].type;
1134 secth [i].sh_addralign = section_info [i].align;
1135 secth [i].sh_flags = section_info [i].flags;
1136 secth [i].sh_entsize = section_info [i].esize;
1138 secth [SECT_DYNSYM].sh_info = SIZEOF_VOID_P == 4 ? 4 : 2;
1139 secth [SECT_SYMTAB].sh_info = SIZEOF_VOID_P == 4 ? 20 : 17;
1140 secth [SECT_HASH].sh_link = SECT_DYNSYM;
1141 secth [SECT_DYNSYM].sh_link = SECT_DYNSTR;
1142 secth [SECT_REL_DYN].sh_link = SECT_DYNSYM;
1143 secth [SECT_RELA_DYN].sh_link = SECT_DYNSYM;
1144 secth [SECT_DYNAMIC].sh_link = SECT_DYNSTR;
1145 secth [SECT_SYMTAB].sh_link = SECT_STRTAB;
1147 num_sections = collect_sections (acfg, secth, all_sections, 8);
1148 hash = build_hash (acfg, num_sections, &dyn_str_table);
1149 num_symtab = hash [1]; /* FIXME */
1150 g_print ("num_sections: %d\n", num_sections);
1151 g_print ("dynsym: %d, dynstr size: %d\n", hash [1], (int)dyn_str_table.data->len);
1152 for (i = 0; i < num_sections; ++i) {
1153 g_print ("section %s, size: %d, %x\n", all_sections [i]->name, all_sections [i]->cur_offset, all_sections [i]->cur_offset);
1156 /* Associate the bin sections with the ELF sections */
1157 memset (sections, 0, sizeof (sections));
1158 for (i = 0; i < num_sections; ++i) {
1159 BinSection *sect = all_sections [i];
1162 for (j = 0; j < SECT_NUM; ++j) {
1163 if (strcmp (sect->name, section_info [j].name) == 0) {
1169 sections [all_sections [i]->shidx] = sect;
1172 /* at this point we know where in the file the first segment sections go */
1173 dynsym = collect_syms (acfg, hash, &dyn_str_table, NULL, NULL);
1174 num_local_syms = hash [1];
1175 symtab = collect_syms (acfg, NULL, &str_table, secth, &num_local_syms);
1177 file_offset = virt_offset = sizeof (header) + sizeof (progh);
1178 secth [SECT_HASH].sh_addr = secth [SECT_HASH].sh_offset = file_offset;
1179 size = sizeof (int) * (2 + hash [0] + hash [1]);
1180 virt_offset = (file_offset += size);
1181 secth [SECT_HASH].sh_size = size;
1182 secth [SECT_DYNSYM].sh_addr = secth [SECT_DYNSYM].sh_offset = file_offset;
1183 size = sizeof (ElfSymbol) * hash [1];
1184 virt_offset = (file_offset += size);
1185 secth [SECT_DYNSYM].sh_size = size;
1186 secth [SECT_DYNSTR].sh_addr = secth [SECT_DYNSTR].sh_offset = file_offset;
1187 size = dyn_str_table.data->len;
1188 virt_offset = (file_offset += size);
1189 secth [SECT_DYNSTR].sh_size = size;
1191 file_offset &= ~(4-1);
1192 secth [SECT_REL_DYN].sh_addr = secth [SECT_REL_DYN].sh_offset = file_offset;
1193 #ifndef USE_ELF_RELA
1194 size = sizeof (ElfReloc) * acfg->num_relocs;
1198 virt_offset = (file_offset += size);
1199 secth [SECT_REL_DYN].sh_size = size;
1200 secth [SECT_RELA_DYN].sh_addr = secth [SECT_RELA_DYN].sh_offset = file_offset;
1202 size = sizeof (ElfRelocA) * acfg->num_relocs;
1206 virt_offset = (file_offset += size);
1207 secth [SECT_RELA_DYN].sh_size = size;
1209 file_offset = ALIGN_TO (file_offset, secth [SECT_TEXT].sh_addralign);
1210 virt_offset = file_offset;
1211 secth [SECT_TEXT].sh_addr = secth [SECT_TEXT].sh_offset = file_offset;
1212 if (sections [SECT_TEXT]) {
1213 size = sections [SECT_TEXT]->cur_offset;
1214 secth [SECT_TEXT].sh_size = size;
1215 file_offset += size;
1218 file_offset = ALIGN_TO (file_offset, secth [SECT_DYNAMIC].sh_addralign);
1219 virt_offset = file_offset;
1221 /* .dynamic, .got.plt, .data, .bss here */
1222 /* Have to increase the virt offset since these go to a separate segment */
1223 virt_offset += PAGESIZE;
1224 secth [SECT_DYNAMIC].sh_addr = virt_offset;
1225 secth [SECT_DYNAMIC].sh_offset = file_offset;
1226 size = sizeof (dynamic);
1227 secth [SECT_DYNAMIC].sh_size = size;
1228 file_offset += size;
1229 virt_offset += size;
1231 file_offset = ALIGN_TO (file_offset, secth [SECT_GOT_PLT].sh_addralign);
1232 virt_offset = ALIGN_TO (virt_offset, secth [SECT_GOT_PLT].sh_addralign);
1233 secth [SECT_GOT_PLT].sh_addr = virt_offset;
1234 secth [SECT_GOT_PLT].sh_offset = file_offset;
1236 secth [SECT_GOT_PLT].sh_size = size;
1237 file_offset += size;
1238 virt_offset += size;
1240 file_offset = ALIGN_TO (file_offset, secth [SECT_DATA].sh_addralign);
1241 virt_offset = ALIGN_TO (virt_offset, secth [SECT_DATA].sh_addralign);
1242 secth [SECT_DATA].sh_addr = virt_offset;
1243 secth [SECT_DATA].sh_offset = file_offset;
1244 if (sections [SECT_DATA]) {
1245 size = sections [SECT_DATA]->cur_offset;
1246 secth [SECT_DATA].sh_size = size;
1247 file_offset += size;
1248 virt_offset += size;
1251 file_offset = ALIGN_TO (file_offset, secth [SECT_BSS].sh_addralign);
1252 virt_offset = ALIGN_TO (virt_offset, secth [SECT_BSS].sh_addralign);
1253 secth [SECT_BSS].sh_addr = virt_offset;
1254 secth [SECT_BSS].sh_offset = file_offset;
1255 if (sections [SECT_BSS]) {
1256 size = sections [SECT_BSS]->cur_offset;
1257 secth [SECT_BSS].sh_size = size;
1260 /* virtual doesn't matter anymore */
1261 file_offset = ALIGN_TO (file_offset, secth [SECT_DEBUG_FRAME].sh_addralign);
1262 secth [SECT_DEBUG_FRAME].sh_offset = file_offset;
1263 if (sections [SECT_DEBUG_FRAME])
1264 size = sections [SECT_DEBUG_FRAME]->cur_offset;
1267 secth [SECT_DEBUG_FRAME].sh_size = size;
1268 file_offset += size;
1270 secth [SECT_DEBUG_INFO].sh_offset = file_offset;
1271 if (sections [SECT_DEBUG_INFO])
1272 size = sections [SECT_DEBUG_INFO]->cur_offset;
1275 secth [SECT_DEBUG_INFO].sh_size = size;
1276 file_offset += size;
1278 secth [SECT_DEBUG_ABBREV].sh_offset = file_offset;
1279 if (sections [SECT_DEBUG_ABBREV])
1280 size = sections [SECT_DEBUG_ABBREV]->cur_offset;
1283 secth [SECT_DEBUG_ABBREV].sh_size = size;
1284 file_offset += size;
1286 file_offset = ALIGN_TO (file_offset, secth [SECT_SHSTRTAB].sh_addralign);
1287 secth [SECT_SHSTRTAB].sh_offset = file_offset;
1288 size = sh_str_table.data->len;
1289 secth [SECT_SHSTRTAB].sh_size = size;
1290 file_offset += size;
1292 file_offset = ALIGN_TO (file_offset, secth [SECT_SYMTAB].sh_addralign);
1293 secth [SECT_SYMTAB].sh_offset = file_offset;
1294 size = sizeof (ElfSymbol) * num_local_syms;
1295 secth [SECT_SYMTAB].sh_size = size;
1296 file_offset += size;
1298 file_offset = ALIGN_TO (file_offset, secth [SECT_STRTAB].sh_addralign);
1299 secth [SECT_STRTAB].sh_offset = file_offset;
1300 size = str_table.data->len;
1301 secth [SECT_STRTAB].sh_size = size;
1302 file_offset += size;
1305 file_offset &= ~(4-1);
1307 header.e_ident [EI_MAG0] = ELFMAG0;
1308 header.e_ident [EI_MAG1] = ELFMAG1;
1309 header.e_ident [EI_MAG2] = ELFMAG2;
1310 header.e_ident [EI_MAG3] = ELFMAG3;
1311 header.e_ident [EI_CLASS] = SIZEOF_VOID_P == 4 ? ELFCLASS32 : ELFCLASS64;
1312 header.e_ident [EI_DATA] = ELFDATA2LSB;
1313 header.e_ident [EI_VERSION] = EV_CURRENT;
1314 header.e_ident [EI_OSABI] = ELFOSABI_NONE;
1315 header.e_ident [EI_ABIVERSION] = 0;
1316 for (i = EI_PAD; i < EI_NIDENT; ++i)
1317 header.e_ident [i] = 0;
1319 header.e_type = ET_DYN;
1320 #if defined(__i386__)
1321 header.e_machine = EM_386;
1322 #elif defined(__x86_64__)
1323 header.e_machine = EM_X86_64;
1324 #elif defined(__arm__)
1325 header.e_machine = EM_ARM;
1327 g_assert_not_reached ();
1329 header.e_version = 1;
1331 header.e_phoff = sizeof (header);
1332 header.e_ehsize = sizeof (header);
1333 header.e_phentsize = sizeof (ElfProgHeader);
1335 header.e_entry = secth [SECT_TEXT].sh_addr;
1336 header.e_shstrndx = SECT_SHSTRTAB;
1337 header.e_shentsize = sizeof (ElfSectHeader);
1338 header.e_shnum = SECT_NUM;
1339 header.e_shoff = file_offset;
1343 dynamic [i].d_tag = DT_HASH;
1344 dynamic [i].d_un.d_val = secth [SECT_HASH].sh_offset;
1346 dynamic [i].d_tag = DT_STRTAB;
1347 dynamic [i].d_un.d_val = secth [SECT_DYNSTR].sh_offset;
1349 dynamic [i].d_tag = DT_SYMTAB;
1350 dynamic [i].d_un.d_val = secth [SECT_DYNSYM].sh_offset;
1352 dynamic [i].d_tag = DT_STRSZ;
1353 dynamic [i].d_un.d_val = dyn_str_table.data->len;
1355 dynamic [i].d_tag = DT_SYMENT;
1356 dynamic [i].d_un.d_val = sizeof (ElfSymbol);
1359 dynamic [i].d_tag = DT_RELA;
1360 dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_offset;
1362 dynamic [i].d_tag = DT_RELASZ;
1363 dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_size;
1365 dynamic [i].d_tag = DT_RELAENT;
1366 dynamic [i].d_un.d_val = sizeof (ElfRelocA);
1369 dynamic [i].d_tag = DT_REL;
1370 dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_offset;
1372 dynamic [i].d_tag = DT_RELSZ;
1373 dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_size;
1375 dynamic [i].d_tag = DT_RELENT;
1376 dynamic [i].d_un.d_val = sizeof (ElfReloc);
1379 dynamic [i].d_tag = DT_RELCOUNT;
1380 dynamic [i].d_un.d_val = acfg->num_relocs;
1383 /* Program header */
1384 memset (&progh, 0, sizeof (progh));
1385 progh [0].p_type = PT_LOAD;
1386 progh [0].p_filesz = progh [0].p_memsz = secth [SECT_DYNAMIC].sh_offset;
1387 progh [0].p_align = 4096;
1388 progh [0].p_flags = 5;
1390 progh [1].p_type = PT_LOAD;
1391 progh [1].p_offset = secth [SECT_DYNAMIC].sh_offset;
1392 progh [1].p_vaddr = progh [1].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1393 progh [1].p_filesz = secth [SECT_BSS].sh_offset - secth [SECT_DYNAMIC].sh_offset;
1394 progh [1].p_memsz = secth [SECT_BSS].sh_addr + secth [SECT_BSS].sh_size - secth [SECT_DYNAMIC].sh_addr;
1395 progh [1].p_align = 4096;
1396 progh [1].p_flags = 6;
1398 progh [2].p_type = PT_DYNAMIC;
1399 progh [2].p_offset = secth [SECT_DYNAMIC].sh_offset;
1400 progh [2].p_vaddr = progh [2].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1401 progh [2].p_filesz = progh [2].p_memsz = secth [SECT_DYNAMIC].sh_size;
1402 progh [2].p_align = SIZEOF_VOID_P;
1403 progh [2].p_flags = 6;
1405 /* Compute the addresses of the bin sections, so relocation can be done */
1406 for (i = 0; i < SECT_NUM; ++i) {
1408 sections [i]->file_offset = secth [i].sh_offset;
1409 sections [i]->virt_offset = secth [i].sh_addr;
1413 reloc_symbols (acfg, dynsym, secth, &dyn_str_table, TRUE);
1414 reloc_symbols (acfg, symtab, secth, &str_table, FALSE);
1415 relocs = resolve_relocations (acfg);
1417 fwrite (&header, sizeof (header), 1, file);
1418 fwrite (&progh, sizeof (progh), 1, file);
1419 fwrite (hash, sizeof (int) * (hash [0] + hash [1] + 2), 1, file);
1420 fwrite (dynsym, sizeof (ElfSymbol) * hash [1], 1, file);
1421 fwrite (dyn_str_table.data->str, dyn_str_table.data->len, 1, file);
1423 fseek (file, secth [SECT_REL_DYN].sh_offset, SEEK_SET);
1424 fwrite (relocs, sizeof (ElfReloc), acfg->num_relocs, file);
1427 fseek (file, secth [SECT_RELA_DYN].sh_offset, SEEK_SET);
1428 fwrite (relocs, secth [SECT_RELA_DYN].sh_size, 1, file);
1431 if (sections [SECT_TEXT]) {
1432 fseek (file, secth [SECT_TEXT].sh_offset, SEEK_SET);
1433 fwrite (sections [SECT_TEXT]->data, sections [SECT_TEXT]->cur_offset, 1, file);
1436 fwrite (dynamic, sizeof (dynamic), 1, file);
1439 size = secth [SECT_DYNAMIC].sh_addr;
1440 fwrite (&size, sizeof (size), 1, file);
1443 if (sections [SECT_DATA]) {
1444 fseek (file, secth [SECT_DATA].sh_offset, SEEK_SET);
1445 fwrite (sections [SECT_DATA]->data, sections [SECT_DATA]->cur_offset, 1, file);
1448 fseek (file, secth [SECT_DEBUG_FRAME].sh_offset, SEEK_SET);
1449 if (sections [SECT_DEBUG_FRAME])
1450 fwrite (sections [SECT_DEBUG_FRAME]->data, sections [SECT_DEBUG_FRAME]->cur_offset, 1, file);
1451 fseek (file, secth [SECT_DEBUG_INFO].sh_offset, SEEK_SET);
1452 if (sections [SECT_DEBUG_INFO])
1453 fwrite (sections [SECT_DEBUG_INFO]->data, sections [SECT_DEBUG_INFO]->cur_offset, 1, file);
1454 fseek (file, secth [SECT_DEBUG_ABBREV].sh_offset, SEEK_SET);
1455 if (sections [SECT_DEBUG_ABBREV])
1456 fwrite (sections [SECT_DEBUG_ABBREV]->data, sections [SECT_DEBUG_ABBREV]->cur_offset, 1, file);
1457 fseek (file, secth [SECT_SHSTRTAB].sh_offset, SEEK_SET);
1458 fwrite (sh_str_table.data->str, sh_str_table.data->len, 1, file);
1459 fseek (file, secth [SECT_SYMTAB].sh_offset, SEEK_SET);
1460 fwrite (symtab, sizeof (ElfSymbol) * num_local_syms, 1, file);
1461 fseek (file, secth [SECT_STRTAB].sh_offset, SEEK_SET);
1462 fwrite (str_table.data->str, str_table.data->len, 1, file);
1463 /*g_print ("file_offset %d vs %d\n", file_offset, ftell (file));*/
1464 /*g_assert (file_offset >= ftell (file));*/
1465 fseek (file, file_offset, SEEK_SET);
1466 fwrite (§h, sizeof (secth), 1, file);
1468 rename (tmp_outfile_name, outfile_name);
1470 g_free (tmp_outfile_name);
1471 g_free (outfile_name);
1476 #endif /* USE_ELF_WRITER */
1478 #endif /* USE_BIN_WRITER */
1483 asm_writer_emit_start (MonoAotCompile *acfg)
1485 if (acfg->aot_opts.asm_only) {
1486 if (acfg->aot_opts.outfile)
1487 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1489 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
1490 acfg->fp = fopen (acfg->tmpfname, "w+");
1492 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
1493 acfg->fp = fdopen (i, "w+");
1495 g_assert (acfg->fp);
1499 asm_writer_emit_unset_mode (MonoAotCompile *acfg)
1501 if (acfg->mode == EMIT_NONE)
1503 fprintf (acfg->fp, "\n");
1504 acfg->mode = EMIT_NONE;
1508 asm_writer_emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
1510 asm_writer_emit_unset_mode (acfg);
1511 #if defined(PLATFORM_WIN32)
1512 fprintf (acfg->fp, ".section %s\n", section_name);
1513 #elif defined(__MACH__)
1514 if (strcmp(section_name, ".bss") == 0)
1515 fprintf (acfg->fp, "%s\n", ".data");
1517 fprintf (acfg->fp, "%s\n", section_name);
1518 #elif defined(sparc) || defined(__arm__)
1519 /* For solaris as, GNU as should accept the same */
1520 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1522 if (!strcmp (section_name, ".text") || !strcmp (section_name, ".data") || !strcmp (section_name, ".bss")) {
1523 fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1525 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1526 fprintf (acfg->fp, ".subsection %d\n", subsection_index);
1532 asm_writer_emit_symbol_type (MonoAotCompile *acfg, const char *name, gboolean func)
1541 asm_writer_emit_unset_mode (acfg);
1542 #if defined(__MACH__)
1544 #elif defined(sparc) || defined(__arm__)
1545 fprintf (acfg->fp, "\t.type %s,#%s\n", name, stype);
1546 #elif defined(PLATFORM_WIN32)
1548 #elif defined(__x86_64__) || defined(__i386__)
1549 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1551 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1556 asm_writer_emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
1558 asm_writer_emit_unset_mode (acfg);
1559 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1560 // mach-o always uses a '_' prefix.
1561 fprintf (acfg->fp, "\t.globl _%s\n", name);
1563 fprintf (acfg->fp, "\t.globl %s\n", name);
1566 asm_writer_emit_symbol_type (acfg, name, func);
1570 asm_writer_emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
1572 asm_writer_emit_unset_mode (acfg);
1574 fprintf (acfg->fp, "\t.local %s\n", name);
1576 asm_writer_emit_symbol_type (acfg, name, func);
1580 asm_writer_emit_label (MonoAotCompile *acfg, const char *name)
1582 asm_writer_emit_unset_mode (acfg);
1583 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1584 // mach-o always uses a '_' prefix.
1585 fprintf (acfg->fp, "_%s:\n", name);
1587 fprintf (acfg->fp, "%s:\n", name);
1590 #if defined(PLATFORM_WIN32)
1591 /* Emit a normal label too */
1592 fprintf (acfg->fp, "%s:\n", name);
1597 asm_writer_emit_string (MonoAotCompile *acfg, const char *value)
1599 asm_writer_emit_unset_mode (acfg);
1600 fprintf (acfg->fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
1604 asm_writer_emit_line (MonoAotCompile *acfg)
1606 asm_writer_emit_unset_mode (acfg);
1607 fprintf (acfg->fp, "\n");
1611 asm_writer_emit_alignment (MonoAotCompile *acfg, int size)
1613 asm_writer_emit_unset_mode (acfg);
1614 #if defined(__arm__)
1615 fprintf (acfg->fp, "\t.align %d\n", ilog2 (size));
1616 #elif defined(__ppc__) && defined(__MACH__)
1617 // the mach-o assembler specifies alignments as powers of 2.
1618 fprintf (acfg->fp, "\t.align %d\t; ilog2\n", ilog2(size));
1619 #elif defined(__powerpc__)
1620 /* ignore on linux/ppc */
1622 fprintf (acfg->fp, "\t.align %d\n", size);
1627 asm_writer_emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
1629 asm_writer_emit_unset_mode (acfg);
1630 asm_writer_emit_alignment (acfg, sizeof (gpointer));
1631 #if defined(__x86_64__)
1632 fprintf (acfg->fp, "\t.quad %s\n", target ? target : "0");
1633 #elif defined(sparc) && SIZEOF_VOID_P == 8
1634 fprintf (acfg->fp, "\t.xword %s\n", target ? target : "0");
1636 fprintf (acfg->fp, "\t.long %s\n", target ? target : "0");
1641 asm_writer_emit_pointer (MonoAotCompile *acfg, const char *target)
1643 asm_writer_emit_unset_mode (acfg);
1644 asm_writer_emit_alignment (acfg, sizeof (gpointer));
1645 asm_writer_emit_pointer_unaligned (acfg, target);
1648 static char *byte_to_str;
1651 asm_writer_emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
1654 if (acfg->mode != EMIT_BYTE) {
1655 acfg->mode = EMIT_BYTE;
1656 acfg->col_count = 0;
1659 if (byte_to_str == NULL) {
1660 byte_to_str = g_new0 (char, 256 * 8);
1661 for (i = 0; i < 256; ++i) {
1662 sprintf (byte_to_str + (i * 8), ",%d", i);
1666 for (i = 0; i < size; ++i, ++acfg->col_count) {
1667 if ((acfg->col_count % 32) == 0)
1668 fprintf (acfg->fp, "\n\t.byte %d", buf [i]);
1670 fputs (byte_to_str + (buf [i] * 8), acfg->fp);
1675 asm_writer_emit_int16 (MonoAotCompile *acfg, int value)
1677 if (acfg->mode != EMIT_WORD) {
1678 acfg->mode = EMIT_WORD;
1679 acfg->col_count = 0;
1681 if ((acfg->col_count++ % 8) == 0)
1682 #if defined(__MACH__)
1683 fprintf (acfg->fp, "\n\t.short ");
1684 #elif defined(__arm__)
1685 /* FIXME: Use .hword on other archs as well */
1686 fprintf (acfg->fp, "\n\t.hword ");
1688 fprintf (acfg->fp, "\n\t.word ");
1691 fprintf (acfg->fp, ", ");
1692 fprintf (acfg->fp, "%d", value);
1696 asm_writer_emit_int32 (MonoAotCompile *acfg, int value)
1698 if (acfg->mode != EMIT_LONG) {
1699 acfg->mode = EMIT_LONG;
1700 acfg->col_count = 0;
1702 if ((acfg->col_count++ % 8) == 0)
1703 fprintf (acfg->fp, "\n\t.long ");
1705 fprintf (acfg->fp, ",");
1706 fprintf (acfg->fp, "%d", value);
1710 asm_writer_emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
1712 if (acfg->mode != EMIT_LONG) {
1713 acfg->mode = EMIT_LONG;
1714 acfg->col_count = 0;
1716 if ((acfg->col_count++ % 8) == 0)
1717 fprintf (acfg->fp, "\n\t.long ");
1719 fprintf (acfg->fp, ",");
1721 fprintf (acfg->fp, "%s - %s + %d", end, start, offset);
1722 else if (offset < 0)
1723 fprintf (acfg->fp, "%s - %s %d", end, start, offset);
1725 fprintf (acfg->fp, "%s - %s", end, start);
1729 asm_writer_emit_zero_bytes (MonoAotCompile *acfg, int num)
1731 asm_writer_emit_unset_mode (acfg);
1732 #if defined(__MACH__)
1733 fprintf (acfg->fp, "\t.space %d\n", num);
1735 fprintf (acfg->fp, "\t.skip %d\n", num);
1740 asm_writer_emit_writeout (MonoAotCompile *acfg)
1742 char *command, *objfile;
1743 char *outfile_name, *tmp_outfile_name;
1747 #if defined(__x86_64__)
1748 #define AS_OPTIONS "--64"
1749 #elif defined(sparc) && SIZEOF_VOID_P == 8
1750 #define AS_OPTIONS "-xarch=v9"
1752 #define AS_OPTIONS ""
1755 if (acfg->aot_opts.asm_only) {
1756 printf ("Output file: '%s'.\n", acfg->tmpfname);
1757 if (acfg->aot_opts.static_link)
1758 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1762 if (acfg->aot_opts.static_link) {
1763 if (acfg->aot_opts.outfile)
1764 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1766 objfile = g_strdup_printf ("%s.o", acfg->image->name);
1768 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
1770 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
1771 printf ("Executing the native assembler: %s\n", command);
1772 if (system (command) != 0) {
1780 if (acfg->aot_opts.static_link) {
1781 printf ("Output file: '%s'.\n", objfile);
1782 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1787 if (acfg->aot_opts.outfile)
1788 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1790 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1792 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1795 command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
1796 #elif defined(__ppc__) && defined(__MACH__)
1797 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
1798 #elif defined(PLATFORM_WIN32)
1799 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
1801 if (acfg->aot_opts.no_dlsym) {
1803 * Need to link using gcc so our ctor function gets called.
1805 command = g_strdup_printf ("gcc -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1807 command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1810 printf ("Executing the native linker: %s\n", command);
1811 if (system (command) != 0) {
1812 g_free (tmp_outfile_name);
1813 g_free (outfile_name);
1821 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
1822 printf ("Stripping the binary: %s\n", com);
1826 rename (tmp_outfile_name, outfile_name);
1828 g_free (tmp_outfile_name);
1829 g_free (outfile_name);
1832 if (acfg->aot_opts.save_temps)
1833 printf ("Retained input file.\n");
1835 unlink (acfg->tmpfname);
1840 /* EMIT FUNCTIONS */
1842 static void emit_start (MonoAotCompile *acfg)
1844 #ifdef USE_BIN_WRITER
1845 if (acfg->use_bin_writer)
1846 bin_writer_emit_start (acfg);
1848 asm_writer_emit_start (acfg);
1850 asm_writer_emit_start (acfg);
1854 static void emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
1856 #ifdef USE_BIN_WRITER
1857 if (acfg->use_bin_writer)
1858 bin_writer_emit_section_change (acfg, section_name, subsection_index);
1860 asm_writer_emit_section_change (acfg, section_name, subsection_index);
1862 asm_writer_emit_section_change (acfg, section_name, subsection_index);
1866 static void emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
1868 #ifdef USE_BIN_WRITER
1869 if (acfg->use_bin_writer)
1870 bin_writer_emit_global_inner (acfg, name, func);
1872 asm_writer_emit_global_inner (acfg, name, func);
1874 asm_writer_emit_global_inner (acfg, name, func);
1878 static void G_GNUC_UNUSED emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
1880 #ifdef USE_BIN_WRITER
1881 if (acfg->use_bin_writer)
1882 bin_writer_emit_local_symbol (acfg, name, end_label, func);
1884 asm_writer_emit_local_symbol (acfg, name, end_label, func);
1886 asm_writer_emit_local_symbol (acfg, name, end_label, func);
1890 static void emit_label (MonoAotCompile *acfg, const char *name)
1892 #ifdef USE_BIN_WRITER
1893 if (acfg->use_bin_writer)
1894 bin_writer_emit_label (acfg, name);
1896 asm_writer_emit_label (acfg, name);
1898 asm_writer_emit_label (acfg, name);
1902 static void emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
1904 #ifdef USE_BIN_WRITER
1905 if (acfg->use_bin_writer)
1906 bin_writer_emit_bytes (acfg, buf, size);
1908 asm_writer_emit_bytes (acfg, buf, size);
1910 asm_writer_emit_bytes (acfg, buf, size);
1914 static void emit_string (MonoAotCompile *acfg, const char *value)
1916 #ifdef USE_BIN_WRITER
1917 if (acfg->use_bin_writer)
1918 bin_writer_emit_string (acfg, value);
1920 asm_writer_emit_string (acfg, value);
1922 asm_writer_emit_string (acfg, value);
1926 static void emit_line (MonoAotCompile *acfg)
1928 #ifdef USE_BIN_WRITER
1929 if (acfg->use_bin_writer)
1930 bin_writer_emit_line (acfg);
1932 asm_writer_emit_line (acfg);
1934 asm_writer_emit_line (acfg);
1938 static void emit_alignment (MonoAotCompile *acfg, int size)
1940 #ifdef USE_BIN_WRITER
1941 if (acfg->use_bin_writer)
1942 bin_writer_emit_alignment (acfg, size);
1944 asm_writer_emit_alignment (acfg, size);
1946 asm_writer_emit_alignment (acfg, size);
1950 static void emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
1952 #ifdef USE_BIN_WRITER
1953 if (acfg->use_bin_writer)
1954 bin_writer_emit_pointer_unaligned (acfg, target);
1956 asm_writer_emit_pointer_unaligned (acfg, target);
1958 asm_writer_emit_pointer_unaligned (acfg, target);
1962 static void emit_pointer (MonoAotCompile *acfg, const char *target)
1964 #ifdef USE_BIN_WRITER
1965 if (acfg->use_bin_writer)
1966 bin_writer_emit_pointer (acfg, target);
1968 asm_writer_emit_pointer (acfg, target);
1970 asm_writer_emit_pointer (acfg, target);
1974 static void emit_int16 (MonoAotCompile *acfg, int value)
1976 #ifdef USE_BIN_WRITER
1977 if (acfg->use_bin_writer)
1978 bin_writer_emit_int16 (acfg, value);
1980 asm_writer_emit_int16 (acfg, value);
1982 asm_writer_emit_int16 (acfg, value);
1986 static void emit_int32 (MonoAotCompile *acfg, int value)
1988 #ifdef USE_BIN_WRITER
1989 if (acfg->use_bin_writer)
1990 bin_writer_emit_int32 (acfg, value);
1992 asm_writer_emit_int32 (acfg, value);
1994 asm_writer_emit_int32 (acfg, value);
1998 static void emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
2000 #ifdef USE_BIN_WRITER
2001 if (acfg->use_bin_writer)
2002 bin_writer_emit_symbol_diff (acfg, end, start, offset);
2004 asm_writer_emit_symbol_diff (acfg, end, start, offset);
2006 asm_writer_emit_symbol_diff (acfg, end, start, offset);
2010 static void emit_zero_bytes (MonoAotCompile *acfg, int num)
2012 #ifdef USE_BIN_WRITER
2013 if (acfg->use_bin_writer)
2014 bin_writer_emit_zero_bytes (acfg, num);
2016 asm_writer_emit_zero_bytes (acfg, num);
2018 asm_writer_emit_zero_bytes (acfg, num);
2023 emit_writeout (MonoAotCompile *acfg)
2025 #ifdef USE_BIN_WRITER
2026 if (acfg->use_bin_writer)
2027 return bin_writer_emit_writeout (acfg);
2029 return asm_writer_emit_writeout (acfg);
2031 return asm_writer_emit_writeout (acfg);
2036 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
2038 if (acfg->aot_opts.no_dlsym) {
2039 g_ptr_array_add (acfg->globals, g_strdup (name));
2041 emit_global_inner (acfg, name, func);
2046 emit_byte (MonoAotCompile *acfg, guint8 val)
2048 emit_bytes (acfg, &val, 1);
2052 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
2054 emit_section_change (acfg, ".text", 1);
2055 emit_global (acfg, name, FALSE);
2056 emit_label (acfg, name);
2057 emit_string (acfg, value);
2063 mono_get_field_token (MonoClassField *field)
2065 MonoClass *klass = field->parent;
2068 for (i = 0; i < klass->field.count; ++i) {
2069 if (field == &klass->fields [i])
2070 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2073 g_assert_not_reached ();
2078 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2082 //printf ("ENCODE: %d 0x%x.\n", value, value);
2085 * Same encoding as the one used in the metadata, extended to handle values
2086 * greater than 0x1fffffff.
2088 if ((value >= 0) && (value <= 127))
2090 else if ((value >= 0) && (value <= 16383)) {
2091 p [0] = 0x80 | (value >> 8);
2092 p [1] = value & 0xff;
2094 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2095 p [0] = (value >> 24) | 0xc0;
2096 p [1] = (value >> 16) & 0xff;
2097 p [2] = (value >> 8) & 0xff;
2098 p [3] = value & 0xff;
2103 p [1] = (value >> 24) & 0xff;
2104 p [2] = (value >> 16) & 0xff;
2105 p [3] = (value >> 8) & 0xff;
2106 p [4] = value & 0xff;
2114 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2118 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2122 index = g_hash_table_size (cfg->image_hash);
2123 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2124 g_ptr_array_add (cfg->image_table, image);
2130 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2133 MonoClass *k = NULL;
2135 /* FIXME: Search referenced images as well */
2136 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2137 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2142 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
2143 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2149 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2154 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2155 * standard metadata encoding.
2158 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2162 if (klass->generic_class) {
2164 g_assert (klass->type_token);
2166 /* Find a typespec for a class if possible */
2167 token = find_typespec_for_class (acfg, klass);
2169 encode_value (token, p, &p);
2170 encode_value (get_image_index (acfg, acfg->image), p, &p);
2172 MonoClass *gclass = klass->generic_class->container_class;
2173 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2176 /* Encode it ourselves */
2178 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
2179 encode_value (MONO_TYPE_GENERICINST, p, &p);
2180 encode_klass_ref (acfg, gclass, p, &p);
2181 encode_value (inst->type_argc, p, &p);
2182 for (i = 0; i < inst->type_argc; ++i)
2183 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2185 } else if (klass->type_token) {
2186 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2187 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2188 encode_value (get_image_index (acfg, klass->image), p, &p);
2189 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2190 MonoGenericParam *param = klass->byval_arg.data.generic_param;
2193 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
2194 encode_value (klass->byval_arg.type, p, &p);
2196 encode_value (param->num, p, &p);
2198 g_assert (param->owner);
2199 encode_value (param->owner->is_method, p, &p);
2200 if (param->owner->is_method)
2201 encode_method_ref (acfg, param->owner->owner.method, p, &p);
2203 encode_klass_ref (acfg, param->owner->owner.klass, p, &p);
2206 g_assert (klass->rank > 0);
2207 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
2208 encode_value (get_image_index (acfg, klass->image), p, &p);
2209 encode_value (klass->rank, p, &p);
2210 encode_klass_ref (acfg, klass->element_class, p, &p);
2216 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2218 guint32 token = mono_get_field_token (field);
2221 encode_klass_ref (cfg, field->parent, p, &p);
2222 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2223 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2228 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2232 MonoGenericInst *inst;
2234 /* Encode the context */
2235 inst = context->class_inst;
2236 encode_value (inst ? 1 : 0, p, &p);
2238 encode_value (inst->type_argc, p, &p);
2239 for (i = 0; i < inst->type_argc; ++i)
2240 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2242 inst = context->method_inst;
2243 encode_value (inst ? 1 : 0, p, &p);
2245 encode_value (inst->type_argc, p, &p);
2246 for (i = 0; i < inst->type_argc; ++i)
2247 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2253 #define MAX_IMAGE_INDEX 250
2256 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2258 guint32 image_index = get_image_index (acfg, method->klass->image);
2259 guint32 token = method->token;
2260 MonoJumpInfoToken *ji;
2263 g_assert (image_index < MAX_IMAGE_INDEX);
2265 /* Mark methods which can't use aot trampolines because they need the further
2266 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2268 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2269 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2270 encode_value ((252 << 24), p, &p);
2272 if (method->wrapper_type) {
2274 encode_value ((253 << 24), p, &p);
2276 encode_value (method->wrapper_type, p, &p);
2278 switch (method->wrapper_type) {
2279 case MONO_WRAPPER_REMOTING_INVOKE:
2280 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2281 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2284 m = mono_marshal_method_from_wrapper (method);
2286 encode_method_ref (acfg, m, p, &p);
2289 case MONO_WRAPPER_PROXY_ISINST:
2290 case MONO_WRAPPER_LDFLD:
2291 case MONO_WRAPPER_LDFLDA:
2292 case MONO_WRAPPER_STFLD:
2293 case MONO_WRAPPER_ISINST: {
2294 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
2295 encode_klass_ref (acfg, proxy_class, p, &p);
2298 case MONO_WRAPPER_LDFLD_REMOTE:
2299 case MONO_WRAPPER_STFLD_REMOTE:
2301 case MONO_WRAPPER_ALLOC: {
2302 int alloc_type = mono_gc_get_managed_allocator_type (method);
2303 g_assert (alloc_type != -1);
2304 encode_value (alloc_type, p, &p);
2307 case MONO_WRAPPER_STELEMREF:
2309 case MONO_WRAPPER_UNKNOWN:
2310 if (strcmp (method->name, "FastMonitorEnter") == 0)
2311 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
2312 else if (strcmp (method->name, "FastMonitorExit") == 0)
2313 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
2315 g_assert_not_reached ();
2317 case MONO_WRAPPER_STATIC_RGCTX_INVOKE: {
2320 m = mono_marshal_method_from_wrapper (method);
2322 encode_method_ref (acfg, m, p, &p);
2326 g_assert_not_reached ();
2328 } else if (mono_method_signature (method)->is_inflated) {
2330 * This is a generic method, find the original token which referenced it and
2332 * Obtain the token from information recorded by the JIT.
2334 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2336 image_index = get_image_index (acfg, ji->image);
2337 g_assert (image_index < MAX_IMAGE_INDEX);
2341 encode_value ((255 << 24), p, &p);
2342 encode_value (image_index, p, &p);
2343 encode_value (token, p, &p);
2345 MonoMethod *declaring;
2346 MonoGenericContext *context = mono_method_get_context (method);
2348 g_assert (method->is_inflated);
2349 declaring = ((MonoMethodInflated*)method)->declaring;
2352 * This might be a non-generic method of a generic instance, which
2353 * doesn't have a token since the reference is generated by the JIT
2354 * like Nullable:Box/Unbox, or by generic sharing.
2358 encode_value ((254 << 24), p, &p);
2359 /* Encode the klass */
2360 encode_klass_ref (acfg, method->klass, p, &p);
2361 /* Encode the method */
2362 image_index = get_image_index (acfg, method->klass->image);
2363 g_assert (image_index < MAX_IMAGE_INDEX);
2364 g_assert (declaring->token);
2365 token = declaring->token;
2366 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2367 encode_value (image_index, p, &p);
2368 encode_value (token, p, &p);
2369 encode_generic_context (acfg, context, p, &p);
2371 } else if (token == 0) {
2372 /* This might be a method of a constructed type like int[,].Set */
2373 /* Obtain the token from information recorded by the JIT */
2374 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2376 image_index = get_image_index (acfg, ji->image);
2377 g_assert (image_index < MAX_IMAGE_INDEX);
2381 encode_value ((255 << 24), p, &p);
2382 encode_value (image_index, p, &p);
2383 encode_value (token, p, &p);
2385 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2386 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2392 compare_patches (gconstpointer a, gconstpointer b)
2396 i = (*(MonoJumpInfo**)a)->ip.i;
2397 j = (*(MonoJumpInfo**)b)->ip.i;
2411 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2414 static inline gboolean
2415 is_plt_patch (MonoJumpInfo *patch_info)
2417 switch (patch_info->type) {
2418 case MONO_PATCH_INFO_METHOD:
2419 case MONO_PATCH_INFO_INTERNAL_METHOD:
2420 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2421 case MONO_PATCH_INFO_ICALL_ADDR:
2422 case MONO_PATCH_INFO_CLASS_INIT:
2423 case MONO_PATCH_INFO_RGCTX_FETCH:
2424 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2425 case MONO_PATCH_INFO_MONITOR_ENTER:
2426 case MONO_PATCH_INFO_MONITOR_EXIT:
2434 * is_shared_got_patch:
2436 * Return whenever PATCH_INFO refers to a patch which needs a shared GOT
2438 * Keep it in sync with the version in aot-runtime.c.
2440 static inline gboolean
2441 is_shared_got_patch (MonoJumpInfo *patch_info)
2443 switch (patch_info->type) {
2444 case MONO_PATCH_INFO_VTABLE:
2445 case MONO_PATCH_INFO_CLASS:
2446 case MONO_PATCH_INFO_IID:
2447 case MONO_PATCH_INFO_ADJUSTED_IID:
2448 case MONO_PATCH_INFO_FIELD:
2449 case MONO_PATCH_INFO_SFLDA:
2450 case MONO_PATCH_INFO_DECLSEC:
2451 case MONO_PATCH_INFO_LDTOKEN:
2452 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2453 case MONO_PATCH_INFO_RVA:
2454 case MONO_PATCH_INFO_METHODCONST:
2462 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2466 if (is_plt_patch (patch_info)) {
2467 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
2469 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2471 * Allocate a separate PLT slot for each such patch, since some plt
2472 * entries will refer to the method itself, and some will refer to
2481 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2483 res = acfg->plt_offset;
2484 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
2485 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
2486 acfg->plt_offset ++;
2496 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2497 * JI could be found if it exists, otherwise allocates a new one.
2500 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2504 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
2506 return got_offset - 1;
2508 got_offset = acfg->got_offset;
2509 acfg->got_offset ++;
2511 acfg->stats.got_slots ++;
2512 acfg->stats.got_slot_types [ji->type] ++;
2518 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2523 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
2524 got_offset = get_got_offset (acfg, ji);
2525 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
2526 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
2527 g_ptr_array_add (acfg->shared_patches, copy);
2530 return get_got_offset (acfg, ji);
2533 /* Add a method to the list of methods which need to be emitted */
2535 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
2538 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2539 g_ptr_array_add (acfg->methods, method);
2540 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2541 acfg->nmethods = acfg->methods->len + 1;
2546 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2548 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2556 add_method (MonoAotCompile *acfg, MonoMethod *method)
2560 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2564 index = acfg->method_index;
2565 add_method_with_index (acfg, method, index);
2567 /* FIXME: Fix quadratic behavior */
2568 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2570 acfg->method_index ++;
2576 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2580 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2583 add_method (acfg, method);
2584 g_ptr_array_add (acfg->extra_methods, method);
2588 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2590 MonoAotCompile *acfg = user_data;
2591 MonoJitICallInfo *callinfo = value;
2592 MonoMethod *wrapper;
2598 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2599 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2602 add_method (acfg, wrapper);
2606 get_runtime_invoke_sig (MonoMethodSignature *sig)
2608 MonoMethodBuilder *mb;
2611 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2612 m = mono_mb_create_method (mb, sig, 16);
2613 return mono_marshal_get_runtime_invoke (m);
2617 add_wrappers (MonoAotCompile *acfg)
2619 MonoMethod *method, *m;
2620 int i, j, nallocators;
2621 MonoMethodSignature *sig, *csig;
2625 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2626 * so there is only one wrapper of a given type, or inlining their contents into their
2631 * FIXME: This depends on the fact that different wrappers have different
2635 /* FIXME: Collect these automatically */
2637 /* Runtime invoke wrappers */
2639 /* void runtime-invoke () [.cctor] */
2640 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2641 csig->ret = &mono_defaults.void_class->byval_arg;
2642 add_method (acfg, get_runtime_invoke_sig (csig));
2644 /* void runtime-invoke () [Finalize] */
2645 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2647 csig->ret = &mono_defaults.void_class->byval_arg;
2648 add_method (acfg, get_runtime_invoke_sig (csig));
2650 /* void runtime-invoke (string) [exception ctor] */
2651 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2653 csig->ret = &mono_defaults.void_class->byval_arg;
2654 csig->params [0] = &mono_defaults.string_class->byval_arg;
2655 add_method (acfg, get_runtime_invoke_sig (csig));
2657 /* void runtime-invoke (string, string) [exception ctor] */
2658 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2660 csig->ret = &mono_defaults.void_class->byval_arg;
2661 csig->params [0] = &mono_defaults.string_class->byval_arg;
2662 csig->params [1] = &mono_defaults.string_class->byval_arg;
2663 add_method (acfg, get_runtime_invoke_sig (csig));
2665 /* string runtime-invoke () [Exception.ToString ()] */
2666 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2668 csig->ret = &mono_defaults.string_class->byval_arg;
2669 add_method (acfg, get_runtime_invoke_sig (csig));
2671 /* void runtime-invoke (string, Exception) [exception ctor] */
2672 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2674 csig->ret = &mono_defaults.void_class->byval_arg;
2675 csig->params [0] = &mono_defaults.string_class->byval_arg;
2676 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2677 add_method (acfg, get_runtime_invoke_sig (csig));
2679 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2680 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2682 csig->ret = &(mono_class_from_name (
2683 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2684 csig->params [0] = &mono_defaults.string_class->byval_arg;
2685 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2686 add_method (acfg, get_runtime_invoke_sig (csig));
2688 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2690 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2691 gboolean skip = FALSE;
2693 method = mono_get_method (acfg->image, token, NULL);
2695 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2696 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2697 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2700 if (method->is_generic || method->klass->generic_container)
2703 /* Skip methods which can not be handled by get_runtime_invoke () */
2704 sig = mono_method_signature (method);
2705 if ((sig->ret->type == MONO_TYPE_PTR) ||
2706 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2709 for (j = 0; j < sig->param_count; j++) {
2710 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2715 add_method (acfg, mono_marshal_get_runtime_invoke (method));
2718 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2719 MonoMethodDesc *desc;
2720 MonoMethod *orig_method;
2722 /* JIT icall wrappers */
2723 /* FIXME: locking */
2724 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2726 /* Managed Allocators */
2727 nallocators = mono_gc_get_managed_allocator_types ();
2728 for (i = 0; i < nallocators; ++i) {
2729 m = mono_gc_get_managed_allocator_by_type (i);
2731 add_method (acfg, m);
2735 add_method (acfg, mono_marshal_get_stelemref ());
2737 /* Monitor Enter/Exit */
2738 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2739 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2740 g_assert (orig_method);
2741 mono_method_desc_free (desc);
2742 method = mono_monitor_get_fast_path (orig_method);
2744 add_method (acfg, method);
2746 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2747 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2748 g_assert (orig_method);
2749 mono_method_desc_free (desc);
2750 method = mono_monitor_get_fast_path (orig_method);
2752 add_method (acfg, method);
2755 /* remoting-invoke wrappers */
2756 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2757 MonoMethodSignature *sig;
2759 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2760 method = mono_get_method (acfg->image, token, NULL);
2762 sig = mono_method_signature (method);
2764 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
2765 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2766 m = mono_marshal_get_remoting_invoke_with_check (method);
2768 add_method (acfg, m);
2772 /* delegate-invoke wrappers */
2773 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2776 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2777 klass = mono_class_get (acfg->image, token);
2779 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2780 method = mono_get_delegate_invoke (klass);
2782 m = mono_marshal_get_delegate_invoke (method, NULL);
2784 add_method (acfg, m);
2788 /* Synchronized wrappers */
2789 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2790 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2791 method = mono_get_method (acfg->image, token, NULL);
2793 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
2794 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2798 /* static rgctx wrappers */
2799 /* FIXME: Each wrapper belongs to a given instantiation of a generic method */
2800 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2801 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2802 method = mono_get_method (acfg->image, token, NULL);
2804 if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
2805 (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
2806 mono_class_generic_sharing_enabled (method->klass) &&
2807 mono_method_is_generic_sharable_impl (method, FALSE)) {
2808 m = mono_marshal_get_static_rgctx_invoke (method);
2809 add_method (acfg, m);
2814 /* pinvoke wrappers */
2815 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2817 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2819 method = mono_get_method (acfg->image, token, NULL);
2821 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
2822 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2827 has_type_vars (MonoClass *klass)
2829 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2832 return has_type_vars (klass->element_class);
2833 if (klass->generic_class) {
2834 MonoGenericContext *context = &klass->generic_class->context;
2835 if (context->class_inst) {
2838 for (i = 0; i < context->class_inst->type_argc; ++i)
2839 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2847 method_has_type_vars (MonoMethod *method)
2849 if (has_type_vars (method->klass))
2852 if (method->is_inflated) {
2853 MonoGenericContext *context = mono_method_get_context (method);
2854 if (context->method_inst) {
2857 for (i = 0; i < context->method_inst->type_argc; ++i)
2858 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2866 * add_generic_instances:
2868 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2871 add_generic_instances (MonoAotCompile *acfg)
2876 MonoGenericContext *context;
2878 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2879 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2880 method = mono_get_method (acfg->image, token, NULL);
2882 context = mono_method_get_context (method);
2883 if (context && ((context->class_inst && context->class_inst->is_open) ||
2884 (context->method_inst && context->method_inst->is_open)))
2887 if (method->klass->image != acfg->image)
2890 if (mono_method_is_generic_sharable_impl (method, FALSE))
2894 add_extra_method (acfg, method);
2897 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2901 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2903 klass = mono_class_get (acfg->image, token);
2906 mono_class_init (klass);
2908 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2911 if (has_type_vars (klass))
2914 if (!klass->generic_class && !klass->rank)
2918 * Add rgctx wrappers for cctors since those are called by the runtime, so
2919 * there is no methodspec for them. This is needed even for shared classes,
2920 * since rgctx wrappers belong to inflated methods.
2922 method = mono_class_get_cctor (klass);
2924 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
2927 while ((method = mono_class_get_methods (klass, &iter))) {
2928 if (mono_method_is_generic_sharable_impl (method, FALSE))
2932 if (method->is_generic)
2937 * FIXME: Instances which are referenced by these methods are not added,
2938 * for example Array.Resize<int> for List<int>.Add ().
2940 add_extra_method (acfg, method);
2946 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2948 int i, pindex, start_index, method_index;
2950 MonoJumpInfo *patch_info;
2951 MonoMethodHeader *header;
2952 gboolean skip, direct_call;
2954 char direct_call_target [128];
2957 header = mono_method_get_header (method);
2959 method_index = get_method_index (acfg, method);
2962 /* Collect and sort relocations */
2963 patches = g_ptr_array_new ();
2964 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2965 g_ptr_array_add (patches, patch_info);
2966 g_ptr_array_sort (patches, compare_patches);
2969 for (i = 0; i < code_len; i++) {
2971 for (pindex = start_index; pindex < patches->len; ++pindex) {
2972 patch_info = g_ptr_array_index (patches, pindex);
2973 if (patch_info->ip.i >= i)
2977 #ifdef MONO_ARCH_AOT_SUPPORTED
2979 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2980 start_index = pindex;
2982 switch (patch_info->type) {
2983 case MONO_PATCH_INFO_NONE:
2985 case MONO_PATCH_INFO_GOT_OFFSET: {
2986 guint32 offset = mono_arch_get_patch_offset (code + i);
2987 emit_bytes (acfg, code + i, offset);
2988 emit_symbol_diff (acfg, "got", ".", offset);
2990 i += offset + 4 - 1;
2995 if (!is_got_patch (patch_info->type))
2999 * If this patch is a call, try emitting a direct call instead of
3000 * through a PLT entry. This is possible if the called method is in
3001 * the same assembly and requires no initialization.
3003 direct_call = FALSE;
3004 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
3005 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3007 gboolean direct_callable = TRUE;
3009 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3010 direct_callable = FALSE;
3011 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
3012 // FIXME: Maybe call the wrapper directly ?
3013 direct_callable = FALSE;
3014 if (direct_callable) {
3015 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3017 sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
3018 patch_info->type = MONO_PATCH_INFO_NONE;
3019 acfg->stats.direct_calls ++;
3023 acfg->stats.all_calls ++;
3026 if (!got_only && !direct_call) {
3027 int plt_offset = get_plt_offset (acfg, patch_info);
3028 if (plt_offset != -1) {
3029 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3031 sprintf (direct_call_target, ".Lp_%d", plt_offset);
3033 /* Nullify the patch */
3034 patch_info->type = MONO_PATCH_INFO_NONE;
3039 #if defined(__i386__) || defined(__x86_64__)
3040 g_assert (code [i] == 0xe8);
3041 /* Need to make sure this is exactly 5 bytes long */
3042 emit_byte (acfg, '\xe8');
3043 emit_symbol_diff (acfg, direct_call_target, ".", -4);
3045 #elif defined(__arm__)
3046 #ifdef USE_BIN_WRITER
3054 emit_reloc (acfg, R_ARM_CALL, direct_call_target, -8);
3055 emit_bytes (acfg, buf, 4);
3058 asm_writer_emit_unset_mode (acfg);
3059 fprintf (acfg->fp, "bl %s\n", direct_call_target);
3063 g_assert_not_reached ();
3066 got_slot = get_got_offset (acfg, patch_info);
3068 emit_bytes (acfg, code + i, mono_arch_get_patch_offset (code + i));
3070 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
3071 #elif defined(__i386__)
3072 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
3073 #elif defined(__arm__)
3074 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
3076 g_assert_not_reached ();
3079 i += mono_arch_get_patch_offset (code + i) + 4 - 1;
3085 #endif /* MONO_ARCH_AOT_SUPPORTED */
3088 /* Find next patch */
3090 for (pindex = start_index; pindex < patches->len; ++pindex) {
3091 patch_info = g_ptr_array_index (patches, pindex);
3092 if (patch_info->ip.i >= i)
3096 /* Try to emit multiple bytes at once */
3097 if (pindex < patches->len && patch_info->ip.i > i) {
3098 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3099 i = patch_info->ip.i - 1;
3101 emit_bytes (acfg, code + i, 1);
3108 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3114 int func_alignment = 16;
3115 MonoMethodHeader *header;
3117 method = cfg->orig_method;
3118 code = cfg->native_code;
3119 header = mono_method_get_header (method);
3121 method_index = get_method_index (acfg, method);
3123 /* Make the labels local */
3124 sprintf (symbol, ".Lm_%x", method_index);
3126 emit_alignment (acfg, func_alignment);
3127 emit_label (acfg, symbol);
3129 if (acfg->aot_opts.write_symbols && acfg->use_bin_writer) {
3131 /* Emit a local symbol into the symbol table */
3132 full_name = mono_method_full_name (method, TRUE);
3133 sprintf (symbol, ".Lme_%x", method_index);
3134 emit_local_symbol (acfg, full_name, symbol, TRUE);
3135 emit_label (acfg, full_name);
3139 if (cfg->verbose_level > 0)
3140 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3142 acfg->stats.code_size += cfg->code_len;
3144 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3146 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3150 sprintf (symbol, ".Lme_%x", method_index);
3151 emit_label (acfg, symbol);
3157 * Encode PATCH_INFO into its disk representation.
3160 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3164 switch (patch_info->type) {
3165 case MONO_PATCH_INFO_NONE:
3167 case MONO_PATCH_INFO_IMAGE:
3168 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3170 case MONO_PATCH_INFO_METHOD_REL:
3171 encode_value ((gint)patch_info->data.offset, p, &p);
3173 case MONO_PATCH_INFO_SWITCH: {
3174 gpointer *table = (gpointer *)patch_info->data.table->table;
3177 encode_value (patch_info->data.table->table_size, p, &p);
3178 for (k = 0; k < patch_info->data.table->table_size; k++)
3179 encode_value ((int)(gssize)table [k], p, &p);
3182 case MONO_PATCH_INFO_METHODCONST:
3183 case MONO_PATCH_INFO_METHOD:
3184 case MONO_PATCH_INFO_METHOD_JUMP:
3185 case MONO_PATCH_INFO_ICALL_ADDR:
3186 case MONO_PATCH_INFO_METHOD_RGCTX:
3187 encode_method_ref (acfg, patch_info->data.method, p, &p);
3189 case MONO_PATCH_INFO_INTERNAL_METHOD:
3190 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3191 guint32 len = strlen (patch_info->data.name);
3193 encode_value (len, p, &p);
3195 memcpy (p, patch_info->data.name, len);
3200 case MONO_PATCH_INFO_LDSTR: {
3201 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3202 guint32 token = patch_info->data.token->token;
3203 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3204 encode_value (image_index, p, &p);
3205 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3208 case MONO_PATCH_INFO_RVA:
3209 case MONO_PATCH_INFO_DECLSEC:
3210 case MONO_PATCH_INFO_LDTOKEN:
3211 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3212 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3213 encode_value (patch_info->data.token->token, p, &p);
3214 encode_value (patch_info->data.token->has_context, p, &p);
3215 if (patch_info->data.token->has_context)
3216 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3218 case MONO_PATCH_INFO_EXC_NAME: {
3219 MonoClass *ex_class;
3222 mono_class_from_name (mono_defaults.exception_class->image,
3223 "System", patch_info->data.target);
3224 g_assert (ex_class);
3225 encode_klass_ref (acfg, ex_class, p, &p);
3228 case MONO_PATCH_INFO_R4:
3229 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3231 case MONO_PATCH_INFO_R8:
3232 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3233 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
3235 case MONO_PATCH_INFO_VTABLE:
3236 case MONO_PATCH_INFO_CLASS:
3237 case MONO_PATCH_INFO_IID:
3238 case MONO_PATCH_INFO_ADJUSTED_IID:
3239 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3241 case MONO_PATCH_INFO_CLASS_INIT:
3242 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3243 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3245 case MONO_PATCH_INFO_FIELD:
3246 case MONO_PATCH_INFO_SFLDA:
3247 encode_field_info (acfg, patch_info->data.field, p, &p);
3249 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3251 case MONO_PATCH_INFO_RGCTX_FETCH: {
3252 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3254 encode_method_ref (acfg, entry->method, p, &p);
3255 encode_value (entry->in_mrgctx, p, &p);
3256 encode_value (entry->info_type, p, &p);
3257 encode_value (entry->data->type, p, &p);
3258 encode_patch (acfg, entry->data, p, &p);
3261 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3262 case MONO_PATCH_INFO_MONITOR_ENTER:
3263 case MONO_PATCH_INFO_MONITOR_EXIT:
3266 g_warning ("unable to handle jump info %d", patch_info->type);
3267 g_assert_not_reached ();
3274 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3277 guint32 last_offset, j, pindex;
3278 MonoJumpInfo *patch_info;
3280 encode_value (n_patches, p, &p);
3283 encode_value (first_got_offset, p, &p);
3285 /* First encode the type+position table */
3288 for (pindex = 0; pindex < patches->len; ++pindex) {
3290 patch_info = g_ptr_array_index (patches, pindex);
3292 if (patch_info->type == MONO_PATCH_INFO_NONE)
3297 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
3298 offset = patch_info->ip.i - last_offset;
3299 last_offset = patch_info->ip.i;
3301 /* Only the type is needed */
3302 *p = patch_info->type;
3306 /* Then encode the other info */
3307 for (pindex = 0; pindex < patches->len; ++pindex) {
3308 patch_info = g_ptr_array_index (patches, pindex);
3310 if (is_shared_got_patch (patch_info)) {
3311 guint32 offset = get_got_offset (acfg, patch_info);
3312 encode_value (offset, p, &p);
3314 encode_patch (acfg, patch_info, p, &p);
3322 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3326 int pindex, buf_size, n_patches;
3330 MonoJumpInfo *patch_info;
3331 MonoMethodHeader *header;
3332 guint32 method_index;
3334 guint32 first_got_offset;
3336 method = cfg->orig_method;
3337 code = cfg->native_code;
3338 header = mono_method_get_header (method);
3340 method_index = get_method_index (acfg, method);
3342 /* Make the labels local */
3343 sprintf (symbol, ".Lm_%x_p", method_index);
3345 /* Sort relocations */
3346 patches = g_ptr_array_new ();
3347 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3348 g_ptr_array_add (patches, patch_info);
3349 g_ptr_array_sort (patches, compare_patches);
3351 first_got_offset = acfg->cfgs [method_index]->got_offset;
3353 /**********************/
3354 /* Encode method info */
3355 /**********************/
3357 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3358 p = buf = g_malloc (buf_size);
3360 if (mono_class_get_cctor (method->klass))
3361 encode_klass_ref (acfg, method->klass, p, &p);
3363 /* Not needed when loading the method */
3364 encode_value (0, p, &p);
3367 if (cfg->opt & MONO_OPT_SHARED) {
3368 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3369 for (l = cfg->ldstr_list; l; l = l->next) {
3370 encode_value ((long)l->data, p, &p);
3374 /* Used only in shared mode */
3375 g_assert (!cfg->ldstr_list);
3378 for (pindex = 0; pindex < patches->len; ++pindex) {
3379 patch_info = g_ptr_array_index (patches, pindex);
3381 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3382 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3383 patch_info->type = MONO_PATCH_INFO_NONE;
3388 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3389 /* Stored in a GOT slot initialized at module load time */
3390 patch_info->type = MONO_PATCH_INFO_NONE;
3394 if (is_plt_patch (patch_info)) {
3395 /* Calls are made through the PLT */
3396 patch_info->type = MONO_PATCH_INFO_NONE;
3404 g_assert (cfg->has_got_slots);
3406 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3408 acfg->stats.info_size += p - buf;
3410 /* Emit method info */
3412 emit_label (acfg, symbol);
3414 g_assert (p - buf < buf_size);
3415 emit_bytes (acfg, buf, p - buf);
3420 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3423 int k, buf_size, method_index;
3424 guint32 debug_info_size;
3427 MonoMethodHeader *header;
3428 guint8 *p, *buf, *debug_info;
3429 MonoJitInfo *jinfo = cfg->jit_info;
3431 method = cfg->orig_method;
3432 code = cfg->native_code;
3433 header = mono_method_get_header (method);
3435 method_index = get_method_index (acfg, method);
3437 /* Make the labels local */
3438 sprintf (symbol, ".Le_%x_p", method_index);
3440 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3442 buf_size = header->num_clauses * 256 + debug_info_size + 128;
3443 p = buf = g_malloc (buf_size);
3445 encode_value (jinfo->code_size, p, &p);
3446 encode_value (jinfo->used_regs, p, &p);
3447 encode_value (jinfo->has_generic_jit_info, p, &p);
3449 /* Exception table */
3450 if (header->num_clauses) {
3451 for (k = 0; k < header->num_clauses; ++k) {
3452 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3454 encode_value (ei->exvar_offset, p, &p);
3456 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
3457 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3459 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3460 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3461 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3465 if (jinfo->has_generic_jit_info) {
3466 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3468 encode_value (gi->has_this ? 1 : 0, p, &p);
3469 encode_value (gi->this_reg, p, &p);
3470 encode_value (gi->this_offset, p, &p);
3473 * Need to encode jinfo->method too, since it is not equal to 'method'
3474 * when using generic sharing.
3476 encode_method_ref (acfg, jinfo->method, p, &p);
3479 g_assert (debug_info_size < buf_size);
3481 encode_value (debug_info_size, p, &p);
3482 if (debug_info_size) {
3483 memcpy (p, debug_info, debug_info_size);
3484 p += debug_info_size;
3485 g_free (debug_info);
3488 acfg->stats.ex_info_size += p - buf;
3492 emit_label (acfg, symbol);
3494 g_assert (p - buf < buf_size);
3495 emit_bytes (acfg, buf, p - buf);
3500 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3502 MonoClass *klass = mono_class_get (acfg->image, token);
3506 gboolean no_special_static, cant_encode;
3507 gpointer iter = NULL;
3509 buf_size = 10240 + (klass->vtable_size * 16);
3510 p = buf = g_malloc (buf_size);
3514 mono_class_init (klass);
3516 mono_class_get_nested_types (klass, &iter);
3517 g_assert (klass->nested_classes_inited);
3519 mono_class_setup_vtable (klass);
3522 * Emit all the information which is required for creating vtables so
3523 * the runtime does not need to create the MonoMethod structures which
3524 * take up a lot of space.
3527 no_special_static = !mono_class_has_special_static_fields (klass);
3529 /* Check whenever we have enough info to encode the vtable */
3530 cant_encode = FALSE;
3531 for (i = 0; i < klass->vtable_size; ++i) {
3532 MonoMethod *cm = klass->vtable [i];
3534 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3538 if (klass->generic_container || cant_encode) {
3539 encode_value (-1, p, &p);
3541 encode_value (klass->vtable_size, p, &p);
3542 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);
3543 if (klass->has_cctor)
3544 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3545 if (klass->has_finalize)
3546 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3548 encode_value (klass->instance_size, p, &p);
3549 encode_value (mono_class_data_size (klass), p, &p);
3550 encode_value (klass->packing_size, p, &p);
3551 encode_value (klass->min_align, p, &p);
3553 for (i = 0; i < klass->vtable_size; ++i) {
3554 MonoMethod *cm = klass->vtable [i];
3557 encode_method_ref (acfg, cm, p, &p);
3559 encode_value (0, p, &p);
3563 acfg->stats.class_info_size += p - buf;
3566 sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
3567 emit_label (acfg, symbol);
3569 g_assert (p - buf < buf_size);
3570 emit_bytes (acfg, buf, p - buf);
3575 * Calls made from AOTed code are routed through a table of jumps similar to the
3576 * ELF PLT (Program Linkage Table). The differences are the following:
3577 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3578 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3579 * jumps. This means the jumps need to be patched when the address of the callee is
3580 * known. Initially the PLT entries jump to code which transfers control to the
3581 * AOT runtime through the first PLT entry.
3584 emit_plt (MonoAotCompile *acfg)
3590 sprintf (symbol, "plt");
3592 emit_section_change (acfg, ".text", 0);
3593 emit_global (acfg, symbol, TRUE);
3595 /* This section will be made read-write by the AOT loader */
3596 emit_alignment (acfg, PAGESIZE);
3598 emit_alignment (acfg, 16);
3600 emit_label (acfg, symbol);
3602 for (i = 0; i < acfg->plt_offset; ++i) {
3604 #if defined(__arm__)
3609 sprintf (label, ".Lp_%d", i);
3610 emit_label (acfg, label);
3613 * The first plt entry is used to transfer code to the AOT loader.
3616 #if defined(__i386__)
3618 /* It is filled up during loading by the AOT loader. */
3619 emit_zero_bytes (acfg, 16);
3621 /* Need to make sure this is 9 bytes long */
3622 emit_byte (acfg, '\xe9');
3623 emit_symbol_diff (acfg, "plt", ".", -4);
3624 emit_int32 (acfg, acfg->plt_got_info_offsets [i]);
3626 #elif defined(__x86_64__)
3628 * We can't emit jumps because they are 32 bits only so they can't be patched.
3629 * So we make indirect calls through GOT entries which are patched by the AOT
3630 * loader to point to .Lpd entries.
3631 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
3633 /* jmpq *<offset>(%rip) */
3634 emit_byte (acfg, '\xff');
3635 emit_byte (acfg, '\x25');
3636 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + i) * sizeof (gpointer)) -4);
3637 /* Used by mono_aot_get_plt_info_offset */
3638 emit_int32 (acfg, acfg->plt_got_info_offsets [i]);
3639 #elif defined(__arm__)
3641 * - optimize OP_AOTCONST implementation
3642 * - optimize the PLT entries
3643 * - optimize SWITCH AOT implementation
3644 * - implement IMT support
3647 #ifdef USE_BIN_WRITER
3648 /* We only emit 1 relocation since we implement it ourselves anyway */
3649 emit_reloc (acfg, R_ARM_ALU_PC_G0_NC, "got", ((acfg->plt_got_offset_base + i) * sizeof (gpointer)) - 8);
3650 /* FIXME: A 2 instruction encoding is sufficient in most cases */
3651 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
3652 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
3653 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
3654 emit_bytes (acfg, buf, code - buf);
3655 /* FIXME: Get rid of this */
3656 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + i) * sizeof (gpointer)));
3657 /* Used by mono_aot_get_plt_info_offset */
3658 emit_int32 (acfg, acfg->plt_got_info_offsets [i]);
3660 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
3661 ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
3662 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
3663 emit_bytes (acfg, buf, code - buf);
3664 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + i) * sizeof (gpointer)));
3665 /* Used by mono_aot_get_plt_info_offset */
3666 emit_int32 (acfg, acfg->plt_got_info_offsets [i]);
3670 g_assert_not_reached ();
3674 sprintf (symbol, "plt_end");
3675 emit_global (acfg, symbol, TRUE);
3676 emit_label (acfg, symbol);
3679 static G_GNUC_UNUSED void
3680 emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code,
3681 guint32 code_size, int got_offset, MonoJumpInfo *ji)
3685 MonoJumpInfo *patch_info;
3691 sprintf (symbol, "%s", name);
3693 emit_section_change (acfg, ".text", 0);
3694 emit_global (acfg, symbol, TRUE);
3695 emit_alignment (acfg, 16);
3696 emit_label (acfg, symbol);
3699 * The code should access everything through the GOT, so we pass
3702 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3706 /* Sort relocations */
3707 patches = g_ptr_array_new ();
3708 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3709 g_ptr_array_add (patches, patch_info);
3710 g_ptr_array_sort (patches, compare_patches);
3712 buf_size = patches->len * 128 + 128;
3713 buf = g_malloc (buf_size);
3716 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3717 g_assert (p - buf < buf_size);
3719 sprintf (symbol, "%s_p", name);
3721 emit_section_change (acfg, ".text", 0);
3722 emit_global (acfg, symbol, FALSE);
3723 emit_label (acfg, symbol);
3725 emit_bytes (acfg, buf, p - buf);
3729 * When running in aot-only mode, we can't create trampolines at runtime, so we create
3730 * a few, and save them in the AOT file. Normal trampolines embed their argument as a
3731 * literal inside the trampoline code, we can't do that here, so instead we embed an offset
3732 * which needs to be added to the trampoline address to get the address of the GOT slot
3733 * which contains the argument value.
3734 * The generated trampolines jump to the generic trampolines using another GOT slot, which
3735 * will be setup by the AOT loader to point to the generic trampoline code of the given
3739 emit_trampolines (MonoAotCompile *acfg)
3743 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3750 if (!acfg->aot_opts.full_aot)
3753 g_assert (acfg->image->assembly);
3755 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3756 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3757 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3759 * Emit the generic trampolines.
3761 * We could save some code by treating the generic trampolines as a wrapper
3762 * method, but that approach has its own complexities, so we choose the simpler
3765 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3766 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, TRUE);
3768 /* Emit trampoline code */
3770 sprintf (symbol, "generic_trampoline_%d", tramp_type);
3772 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3775 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3776 emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL);
3777 #if defined(__x86_64__) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3778 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3779 emit_named_code (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji);
3780 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3781 emit_named_code (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji);
3784 /* Emit the exception related code pieces */
3785 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3786 emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji);
3787 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3788 emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji);
3789 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3790 emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji);
3791 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3792 emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji);
3793 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3794 emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji);
3795 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3796 emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji);
3798 #if defined(__x86_64__) || defined(__arm__)
3799 for (i = 0; i < 128; ++i) {
3802 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3803 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3804 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3805 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3807 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3808 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3809 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3810 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3816 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3820 /* Reserve some entries at the end of the GOT for our use */
3821 acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
3823 sprintf (symbol, "trampolines");
3825 emit_section_change (acfg, ".text", 0);
3826 emit_global (acfg, symbol, TRUE);
3827 emit_alignment (acfg, 16);
3828 emit_label (acfg, symbol);
3830 for (i = 0; i < acfg->num_aot_trampolines; ++i) {
3831 offset = acfg->got_offset + (i * 2);
3834 * The trampolines created here are variations of the specific
3835 * trampolines created in mono_arch_create_specific_trampoline (). The
3837 * - the generic trampoline address is taken from a got slot.
3838 * - the offset of the got slot where the trampoline argument is stored
3839 * is embedded in the instruction stream, and the generic trampoline
3840 * can load the argument by loading the offset, adding it to the
3841 * address of the trampoline to get the address of the got slot, and
3842 * loading the argument from the there.
3844 #if defined(__x86_64__)
3845 /* This should be exactly 16 bytes long */
3846 /* It should work together with the generic trampoline code in tramp-amd64.c */
3847 /* call *<offset>(%rip) */
3848 emit_byte (acfg, '\x41');
3849 emit_byte (acfg, '\xff');
3850 emit_byte (acfg, '\x15');
3851 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
3852 /* This should be relative to the start of the trampoline */
3853 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
3854 emit_zero_bytes (acfg, 5);
3855 #elif defined(__arm__)
3859 /* Generate the trampoline code */
3860 /* This should be exactly 28 bytes long */
3863 ARM_PUSH (code, 0x5fff);
3864 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
3865 /* Load the value from the GOT */
3866 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
3868 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
3869 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
3871 g_assert (code - buf == 20);
3874 emit_bytes (acfg, buf, code - buf);
3875 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
3876 emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
3879 g_assert_not_reached ();
3884 /* Unbox trampolines */
3886 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3888 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3890 char call_target [256];
3892 method = mono_get_method (acfg->image, token, NULL);
3894 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3895 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
3898 sprintf (symbol, "unbox_trampoline_%d", i);
3900 emit_section_change (acfg, ".text", 0);
3901 emit_global (acfg, symbol, TRUE);
3902 emit_label (acfg, symbol);
3904 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
3906 #if defined(__x86_64__)
3911 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (cfg->orig_method), cfg->generic_sharing_context, NULL);
3913 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
3915 emit_bytes (acfg, buf, code - buf);
3917 emit_byte (acfg, '\xe9');
3918 emit_symbol_diff (acfg, call_target, ".", -4);
3920 #elif defined(__arm__)
3927 if (MONO_TYPE_ISSTRUCT (mono_method_signature (cfg->orig_method)->ret))
3930 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
3932 emit_bytes (acfg, buf, code - buf);
3933 /* jump to method */
3934 #if defined(USE_BIN_WRITER)
3936 g_assert_not_reached ();
3938 fprintf (acfg->fp, "\n\tb %s\n", call_target);
3942 g_assert_not_reached ();
3946 acfg->trampoline_got_offset_base = acfg->got_offset;
3948 acfg->got_offset += acfg->num_trampoline_got_entries;
3952 str_begins_with (const char *str1, const char *str2)
3954 int len = strlen (str2);
3955 return strncmp (str1, str2, len) == 0;
3959 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3961 gchar **args, **ptr;
3963 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3964 for (ptr = args; ptr && *ptr; ptr ++) {
3965 const char *arg = *ptr;
3967 if (str_begins_with (arg, "outfile=")) {
3968 opts->outfile = g_strdup (arg + strlen ("outfile="));
3969 } else if (str_begins_with (arg, "save-temps")) {
3970 opts->save_temps = TRUE;
3971 } else if (str_begins_with (arg, "keep-temps")) {
3972 opts->save_temps = TRUE;
3973 } else if (str_begins_with (arg, "write-symbols")) {
3974 opts->write_symbols = TRUE;
3975 } else if (str_begins_with (arg, "metadata-only")) {
3976 opts->metadata_only = TRUE;
3977 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3978 opts->bind_to_runtime_version = TRUE;
3979 } else if (str_begins_with (arg, "full")) {
3980 opts->full_aot = TRUE;
3982 * The no-dlsym option is only useful on the iphone, and even there,
3983 * do to other limitations of the dynamic linker, it doesn't seem to
3984 * work. So disable it for now so we don't have to support it.
3987 } else if (str_begins_with (arg, "no-dlsym")) {
3988 opts->no_dlsym = TRUE;
3990 } else if (str_begins_with (arg, "threads=")) {
3991 opts->nthreads = atoi (arg + strlen ("threads="));
3992 } else if (str_begins_with (arg, "static")) {
3993 opts->static_link = TRUE;
3994 opts->no_dlsym = TRUE;
3995 } else if (str_begins_with (arg, "asmonly")) {
3996 opts->asm_only = TRUE;
3997 } else if (str_begins_with (arg, "asmwriter")) {
3998 opts->asm_writer = TRUE;
4000 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4009 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4011 MonoMethod *method = (MonoMethod*)key;
4012 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4013 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4014 MonoAotCompile *acfg = user_data;
4016 new_ji->image = ji->image;
4017 new_ji->token = ji->token;
4018 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4024 * AOT compile a given method.
4025 * This function might be called by multiple threads, so it must be thread-safe.
4028 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4031 MonoJumpInfo *patch_info;
4034 MonoMethod *wrapped;
4036 if (acfg->aot_opts.metadata_only)
4039 mono_acfg_lock (acfg);
4040 index = get_method_index (acfg, method);
4041 mono_acfg_unlock (acfg);
4043 /* fixme: maybe we can also precompile wrapper methods */
4044 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4045 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4046 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4047 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4051 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4054 wrapped = mono_marshal_method_from_wrapper (method);
4055 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4056 // FIXME: The wrapper should be generic too, but it is not
4059 InterlockedIncrement (&acfg->stats.mcount);
4062 if (method->is_generic || method->klass->generic_container) {
4063 InterlockedIncrement (&acfg->stats.genericcount);
4068 if (acfg->aot_opts.full_aot)
4069 mono_use_imt = FALSE;
4072 * Since these methods are the only ones which are compiled with
4073 * AOT support, and they are not used by runtime startup/shutdown code,
4074 * the runtime will not see AOT methods during AOT compilation,so it
4075 * does not need to support them by creating a fake GOT etc.
4077 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4078 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4079 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4080 InterlockedIncrement (&acfg->stats.genericcount);
4083 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4084 /* Let the exception happen at runtime */
4088 if (cfg->disable_aot) {
4089 //printf ("Skip (other): %s\n", mono_method_full_name (method, TRUE));
4090 InterlockedIncrement (&acfg->stats.ocount);
4091 mono_destroy_compile (cfg);
4095 /* Nullify patches which need no aot processing */
4096 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4097 switch (patch_info->type) {
4098 case MONO_PATCH_INFO_LABEL:
4099 case MONO_PATCH_INFO_BB:
4100 patch_info->type = MONO_PATCH_INFO_NONE;
4107 /* Collect method->token associations from the cfg */
4108 mono_acfg_lock (acfg);
4109 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4110 mono_acfg_unlock (acfg);
4113 * Check for absolute addresses.
4116 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4117 switch (patch_info->type) {
4118 case MONO_PATCH_INFO_ABS:
4119 /* unable to handle this */
4120 //printf ("Skip (abs addr): %s %d\n", mono_method_full_name (method, TRUE), patch_info->type);
4129 InterlockedIncrement (&acfg->stats.abscount);
4130 mono_destroy_compile (cfg);
4135 * Check for wrapper methods we can't encode.
4138 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4139 if ((patch_info->type == MONO_PATCH_INFO_METHODCONST) || (patch_info->type == MONO_PATCH_INFO_METHOD)) {
4140 switch (patch_info->data.method->wrapper_type) {
4141 case MONO_WRAPPER_NONE:
4142 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4143 case MONO_WRAPPER_XDOMAIN_INVOKE:
4144 case MONO_WRAPPER_STFLD:
4145 case MONO_WRAPPER_LDFLD:
4146 case MONO_WRAPPER_LDFLDA:
4147 case MONO_WRAPPER_LDFLD_REMOTE:
4148 case MONO_WRAPPER_STFLD_REMOTE:
4149 case MONO_WRAPPER_STELEMREF:
4150 case MONO_WRAPPER_ISINST:
4151 case MONO_WRAPPER_PROXY_ISINST:
4152 case MONO_WRAPPER_ALLOC:
4153 case MONO_WRAPPER_REMOTING_INVOKE:
4154 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
4155 case MONO_WRAPPER_UNKNOWN:
4158 /* unable to handle this */
4159 //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));
4163 } else if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH) {
4164 MonoJumpInfo *child = patch_info->data.rgctx_entry->data;
4166 if (child->type == MONO_PATCH_INFO_METHODCONST) {
4167 switch (child->data.method->wrapper_type) {
4168 case MONO_WRAPPER_NONE:
4169 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
4179 InterlockedIncrement (&acfg->stats.wrappercount);
4180 mono_destroy_compile (cfg);
4184 /* Lock for the rest of the code */
4185 mono_acfg_lock (acfg);
4188 * Check for methods/klasses we can't encode.
4191 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4192 switch (patch_info->type) {
4193 case MONO_PATCH_INFO_METHOD:
4194 case MONO_PATCH_INFO_METHODCONST:
4195 if (patch_info->data.method->wrapper_type)
4197 if (!patch_info->data.method->token) {
4198 /* The method is part of a constructed type like Int[,].Set (). */
4199 if (!g_hash_table_lookup (acfg->token_info_hash, patch_info->data.method))
4203 case MONO_PATCH_INFO_VTABLE:
4204 case MONO_PATCH_INFO_CLASS_INIT:
4205 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4206 case MONO_PATCH_INFO_CLASS:
4207 case MONO_PATCH_INFO_IID:
4208 case MONO_PATCH_INFO_ADJUSTED_IID:
4209 if (!patch_info->data.klass->type_token)
4210 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))
4219 acfg->stats.ocount++;
4220 mono_destroy_compile (cfg);
4221 mono_acfg_unlock (acfg);
4225 /* Adds generic instances referenced by this method */
4226 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4227 switch (patch_info->type) {
4228 case MONO_PATCH_INFO_METHOD: {
4229 MonoMethod *m = patch_info->data.method;
4230 if (m->is_inflated) {
4231 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4232 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4233 !method_has_type_vars (m))
4234 add_extra_method (acfg, m);
4243 /* Determine whenever the method has GOT slots */
4244 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4245 switch (patch_info->type) {
4246 case MONO_PATCH_INFO_GOT_OFFSET:
4247 case MONO_PATCH_INFO_NONE:
4249 case MONO_PATCH_INFO_IMAGE:
4250 /* The assembly is stored in GOT slot 0 */
4251 if (patch_info->data.image != acfg->image)
4252 cfg->has_got_slots = TRUE;
4255 if (!is_plt_patch (patch_info))
4256 cfg->has_got_slots = TRUE;
4261 if (!cfg->has_got_slots)
4262 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4264 /* Make a copy of the patch info which is in the mempool */
4266 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4268 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4269 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4272 patches = new_patch_info;
4274 patches_end->next = new_patch_info;
4275 patches_end = new_patch_info;
4277 cfg->patch_info = patches;
4279 /* Make a copy of the unwind info */
4281 GSList *l, *unwind_ops;
4285 for (l = cfg->unwind_ops; l; l = l->next) {
4286 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4287 memcpy (op, l->data, sizeof (MonoUnwindOp));
4288 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4290 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4292 /* Make a copy of the argument info */
4295 MonoMethodSignature *sig;
4298 sig = mono_method_signature (method);
4299 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4300 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4301 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4302 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4307 /* Free some fields used by cfg to conserve memory */
4308 mono_mempool_destroy (cfg->mempool);
4309 cfg->mempool = NULL;
4310 g_free (cfg->varinfo);
4311 cfg->varinfo = NULL;
4315 mono_regstate_free (cfg->rs);
4319 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4321 while (index >= acfg->cfgs_size) {
4322 MonoCompile **new_cfgs;
4325 new_size = acfg->cfgs_size * 2;
4326 new_cfgs = g_new0 (MonoCompile*, new_size);
4327 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4328 g_free (acfg->cfgs);
4329 acfg->cfgs = new_cfgs;
4330 acfg->cfgs_size = new_size;
4332 acfg->cfgs [index] = cfg;
4334 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4336 if (cfg->orig_method->wrapper_type)
4337 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4339 mono_acfg_unlock (acfg);
4341 InterlockedIncrement (&acfg->stats.ccount);
4345 compile_thread_main (gpointer *user_data)
4347 MonoDomain *domain = user_data [0];
4348 MonoAotCompile *acfg = user_data [1];
4349 GPtrArray *methods = user_data [2];
4352 mono_thread_attach (domain);
4354 for (i = 0; i < methods->len; ++i)
4355 compile_method (acfg, g_ptr_array_index (methods, i));
4359 load_profile_files (MonoAotCompile *acfg)
4363 int file_index, res, method_index, i;
4370 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);
4372 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4377 infile = fopen (tmp, "r");
4380 printf ("Using profile data file '%s'\n", tmp);
4385 res = fscanf (infile, "%32s\n", ver);
4386 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
4387 printf ("Profile file has wrong version or invalid.\n");
4393 res = fscanf (infile, "%d\n", &token);
4397 method_index = mono_metadata_token_index (token) - 1;
4399 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
4400 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4405 /* Add missing methods */
4407 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4408 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4409 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4411 unordered = g_list_reverse (unordered);
4412 if (acfg->method_order)
4413 g_list_last (acfg->method_order)->next = unordered;
4415 acfg->method_order = unordered;
4421 * Collect all patches which have shared GOT entries and alloc entries for them. The
4422 * rest will get entries allocated during emit_code ().
4425 alloc_got_slots (MonoAotCompile *acfg)
4431 /* Slot 0 is reserved for the address of the current assembly */
4432 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
4433 ji->type = MONO_PATCH_INFO_IMAGE;
4434 ji->data.image = acfg->image;
4436 get_shared_got_offset (acfg, ji);
4438 for (l = acfg->method_order; l != NULL; l = l->next) {
4439 i = GPOINTER_TO_UINT (l->data);
4441 if (acfg->cfgs [i]) {
4442 MonoCompile *cfg = acfg->cfgs [i];
4444 for (ji = cfg->patch_info; ji; ji = ji->next) {
4445 if (is_shared_got_patch (ji))
4446 get_shared_got_offset (acfg, ji);
4453 emit_code (MonoAotCompile *acfg)
4459 sprintf (symbol, "methods");
4460 emit_section_change (acfg, ".text", 0);
4461 emit_global (acfg, symbol, TRUE);
4462 emit_alignment (acfg, 8);
4463 emit_label (acfg, symbol);
4466 * Emit some padding so the local symbol for the first method doesn't have the
4467 * same address as 'methods'.
4469 emit_zero_bytes (acfg, 16);
4471 for (l = acfg->method_order; l != NULL; l = l->next) {
4472 i = GPOINTER_TO_UINT (l->data);
4475 emit_method_code (acfg, acfg->cfgs [i]);
4478 sprintf (symbol, "methods_end");
4479 emit_section_change (acfg, ".text", 0);
4480 emit_global (acfg, symbol, FALSE);
4481 emit_alignment (acfg, 8);
4482 emit_label (acfg, symbol);
4484 sprintf (symbol, "method_offsets");
4485 emit_section_change (acfg, ".text", 1);
4486 emit_global (acfg, symbol, FALSE);
4487 emit_alignment (acfg, 8);
4488 emit_label (acfg, symbol);
4490 for (i = 0; i < acfg->nmethods; ++i) {
4491 if (acfg->cfgs [i]) {
4492 sprintf (symbol, ".Lm_%x", i);
4493 emit_symbol_diff (acfg, symbol, "methods", 0);
4495 emit_int32 (acfg, 0xffffffff);
4502 emit_info (MonoAotCompile *acfg)
4508 /* Emit method info */
4509 sprintf (symbol, "method_info");
4510 emit_section_change (acfg, ".text", 1);
4511 emit_global (acfg, symbol, FALSE);
4512 emit_alignment (acfg, 8);
4513 emit_label (acfg, symbol);
4515 /* To reduce size of generated assembly code */
4516 sprintf (symbol, "mi");
4517 emit_label (acfg, symbol);
4519 for (l = acfg->method_order; l != NULL; l = l->next) {
4520 i = GPOINTER_TO_UINT (l->data);
4523 emit_method_info (acfg, acfg->cfgs [i]);
4526 sprintf (symbol, "method_info_offsets");
4527 emit_section_change (acfg, ".text", 1);
4528 emit_global (acfg, symbol, FALSE);
4529 emit_alignment (acfg, 8);
4530 emit_label (acfg, symbol);
4532 for (i = 0; i < acfg->nmethods; ++i) {
4533 if (acfg->cfgs [i]) {
4534 sprintf (symbol, ".Lm_%x_p", i);
4535 emit_symbol_diff (acfg, symbol, "mi", 0);
4537 emit_int32 (acfg, 0);
4543 typedef struct HashEntry {
4544 guint32 key, value, index;
4545 struct HashEntry *next;
4549 * emit_extra_methods:
4551 * Emit methods which are not in the METHOD table, like wrappers.
4554 emit_extra_methods (MonoAotCompile *acfg)
4556 int i, table_size, buf_size;
4559 guint32 *info_offsets;
4562 HashEntry *entry, *new_entry;
4565 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4567 buf_size = acfg->extra_methods->len * 256 + 256;
4568 p = buf = g_malloc (buf_size);
4570 /* Encode method info */
4572 /* So offsets are > 0 */
4575 for (i = 0; i < acfg->extra_methods->len; ++i) {
4576 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4577 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4583 info_offsets [i] = p - buf;
4585 if (method->wrapper_type) {
4588 // FIXME: Optimize disk usage
4589 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
4590 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4591 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
4594 name = mono_method_full_name (cfg->orig_method, TRUE);
4597 encode_value (1, p, &p);
4598 strcpy ((char*)p, name);
4599 p += strlen (name ) + 1;
4602 encode_value (0, p, &p);
4603 encode_method_ref (acfg, method, p, &p);
4606 g_assert ((p - buf) < buf_size);
4609 g_assert ((p - buf) < buf_size);
4611 /* Emit method info */
4612 sprintf (symbol, "extra_method_info");
4613 emit_section_change (acfg, ".text", 1);
4614 emit_global (acfg, symbol, FALSE);
4615 emit_alignment (acfg, 8);
4616 emit_label (acfg, symbol);
4618 emit_bytes (acfg, buf, p - buf);
4623 * Construct a chained hash table for mapping indexes in extra_method_info to
4626 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4627 table = g_ptr_array_sized_new (table_size);
4628 for (i = 0; i < table_size; ++i)
4629 g_ptr_array_add (table, NULL);
4630 for (i = 0; i < acfg->extra_methods->len; ++i) {
4631 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4632 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4638 key = info_offsets [i];
4639 value = get_method_index (acfg, method);
4641 if (method->wrapper_type) {
4642 hash = g_str_hash (method->name) % table_size;
4645 hash = 0 % table_size;
4648 /* FIXME: Allocate from the mempool */
4649 new_entry = g_new0 (HashEntry, 1);
4650 new_entry->key = key;
4651 new_entry->value = value;
4653 entry = g_ptr_array_index (table, hash);
4654 if (entry == NULL) {
4655 new_entry->index = hash;
4656 g_ptr_array_index (table, hash) = new_entry;
4659 entry = entry->next;
4661 entry->next = new_entry;
4662 new_entry->index = table->len;
4663 g_ptr_array_add (table, new_entry);
4667 /* Emit the table */
4668 sprintf (symbol, "extra_method_table");
4669 emit_section_change (acfg, ".text", 0);
4670 emit_global (acfg, symbol, FALSE);
4671 emit_alignment (acfg, 8);
4672 emit_label (acfg, symbol);
4674 g_assert (table_size < 65000);
4675 emit_int32 (acfg, table_size);
4676 g_assert (table->len < 65000);
4677 for (i = 0; i < table->len; ++i) {
4678 HashEntry *entry = g_ptr_array_index (table, i);
4680 if (entry == NULL) {
4681 emit_int32 (acfg, 0);
4682 emit_int32 (acfg, 0);
4683 emit_int32 (acfg, 0);
4685 g_assert (entry->key > 0);
4686 emit_int32 (acfg, entry->key);
4687 emit_int32 (acfg, entry->value);
4689 emit_int32 (acfg, entry->next->index);
4691 emit_int32 (acfg, 0);
4696 * Emit a table reverse mapping method indexes to their index in extra_method_info.
4697 * This is used by mono_aot_find_jit_info ().
4699 sprintf (symbol, "extra_method_info_offsets");
4700 emit_section_change (acfg, ".text", 0);
4701 emit_global (acfg, symbol, FALSE);
4702 emit_alignment (acfg, 8);
4703 emit_label (acfg, symbol);
4705 emit_int32 (acfg, acfg->extra_methods->len);
4706 for (i = 0; i < acfg->extra_methods->len; ++i) {
4707 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4709 emit_int32 (acfg, get_method_index (acfg, method));
4710 emit_int32 (acfg, info_offsets [i]);
4715 emit_method_order (MonoAotCompile *acfg)
4721 sprintf (symbol, "method_order");
4722 emit_section_change (acfg, ".text", 1);
4723 emit_global (acfg, symbol, FALSE);
4724 emit_alignment (acfg, 8);
4725 emit_label (acfg, symbol);
4727 /* First emit an index table */
4730 for (l = acfg->method_order; l != NULL; l = l->next) {
4731 i = GPOINTER_TO_UINT (l->data);
4733 if (acfg->cfgs [i]) {
4734 if ((index % 1024) == 0) {
4735 emit_int32 (acfg, i);
4743 emit_int32 (acfg, 0xffffff);
4745 /* Then emit the whole method order */
4746 for (l = acfg->method_order; l != NULL; l = l->next) {
4747 i = GPOINTER_TO_UINT (l->data);
4749 if (acfg->cfgs [i]) {
4750 emit_int32 (acfg, i);
4755 sprintf (symbol, "method_order_end");
4756 emit_section_change (acfg, ".text", 1);
4757 emit_global (acfg, symbol, FALSE);
4758 emit_label (acfg, symbol);
4762 emit_exception_info (MonoAotCompile *acfg)
4767 sprintf (symbol, "ex_info");
4768 emit_section_change (acfg, ".text", 1);
4769 emit_global (acfg, symbol, FALSE);
4770 emit_alignment (acfg, 8);
4771 emit_label (acfg, symbol);
4773 /* To reduce size of generated assembly */
4774 sprintf (symbol, "ex");
4775 emit_label (acfg, symbol);
4777 for (i = 0; i < acfg->nmethods; ++i) {
4779 emit_exception_debug_info (acfg, acfg->cfgs [i]);
4782 sprintf (symbol, "ex_info_offsets");
4783 emit_section_change (acfg, ".text", 1);
4784 emit_global (acfg, symbol, FALSE);
4785 emit_alignment (acfg, 8);
4786 emit_label (acfg, symbol);
4788 for (i = 0; i < acfg->nmethods; ++i) {
4789 if (acfg->cfgs [i]) {
4790 sprintf (symbol, ".Le_%x_p", i);
4791 emit_symbol_diff (acfg, symbol, "ex", 0);
4793 emit_int32 (acfg, 0);
4800 emit_class_info (MonoAotCompile *acfg)
4805 sprintf (symbol, "class_info");
4806 emit_section_change (acfg, ".text", 1);
4807 emit_global (acfg, symbol, FALSE);
4808 emit_alignment (acfg, 8);
4809 emit_label (acfg, symbol);
4811 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4812 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4814 sprintf (symbol, "class_info_offsets");
4815 emit_section_change (acfg, ".text", 1);
4816 emit_global (acfg, symbol, FALSE);
4817 emit_alignment (acfg, 8);
4818 emit_label (acfg, symbol);
4820 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4821 sprintf (symbol, ".LK_I_%x", i);
4822 emit_symbol_diff (acfg, symbol, "class_info", 0);
4827 typedef struct ClassNameTableEntry {
4828 guint32 token, index;
4829 struct ClassNameTableEntry *next;
4830 } ClassNameTableEntry;
4833 emit_class_name_table (MonoAotCompile *acfg)
4836 guint32 token, hash;
4841 ClassNameTableEntry *entry, *new_entry;
4844 * Construct a chained hash table for mapping class names to typedef tokens.
4846 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4847 table = g_ptr_array_sized_new (table_size);
4848 for (i = 0; i < table_size; ++i)
4849 g_ptr_array_add (table, NULL);
4850 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4851 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4852 klass = mono_class_get (acfg->image, token);
4853 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4854 hash = g_str_hash (full_name) % table_size;
4857 /* FIXME: Allocate from the mempool */
4858 new_entry = g_new0 (ClassNameTableEntry, 1);
4859 new_entry->token = token;
4861 entry = g_ptr_array_index (table, hash);
4862 if (entry == NULL) {
4863 new_entry->index = hash;
4864 g_ptr_array_index (table, hash) = new_entry;
4867 entry = entry->next;
4869 entry->next = new_entry;
4870 new_entry->index = table->len;
4871 g_ptr_array_add (table, new_entry);
4875 /* Emit the table */
4876 sprintf (symbol, "class_name_table");
4877 emit_section_change (acfg, ".text", 0);
4878 emit_global (acfg, symbol, FALSE);
4879 emit_alignment (acfg, 8);
4880 emit_label (acfg, symbol);
4882 /* FIXME: Optimize memory usage */
4883 g_assert (table_size < 65000);
4884 emit_int16 (acfg, table_size);
4885 g_assert (table->len < 65000);
4886 for (i = 0; i < table->len; ++i) {
4887 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4889 if (entry == NULL) {
4890 emit_int16 (acfg, 0);
4891 emit_int16 (acfg, 0);
4893 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4895 emit_int16 (acfg, entry->next->index);
4897 emit_int16 (acfg, 0);
4903 emit_image_table (MonoAotCompile *acfg)
4909 * The image table is small but referenced in a lot of places.
4910 * So we emit it at once, and reference its elements by an index.
4913 sprintf (symbol, "mono_image_table");
4914 emit_section_change (acfg, ".text", 1);
4915 emit_global (acfg, symbol, FALSE);
4916 emit_alignment (acfg, 8);
4917 emit_label (acfg, symbol);
4919 emit_int32 (acfg, acfg->image_table->len);
4920 for (i = 0; i < acfg->image_table->len; i++) {
4921 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4922 MonoAssemblyName *aname = &image->assembly->aname;
4924 /* FIXME: Support multi-module assemblies */
4925 g_assert (image->assembly->image == image);
4927 emit_string (acfg, image->assembly_name);
4928 emit_string (acfg, image->guid);
4929 emit_string (acfg, aname->culture ? aname->culture : "");
4930 emit_string (acfg, (const char*)aname->public_key_token);
4932 emit_alignment (acfg, 8);
4933 emit_int32 (acfg, aname->flags);
4934 emit_int32 (acfg, aname->major);
4935 emit_int32 (acfg, aname->minor);
4936 emit_int32 (acfg, aname->build);
4937 emit_int32 (acfg, aname->revision);
4942 emit_got_info (MonoAotCompile *acfg)
4945 int i, first_plt_got_patch, buf_size;
4947 guint32 *got_info_offsets;
4949 /* Add the patches needed by the PLT to the GOT */
4950 acfg->plt_got_offset_base = acfg->got_offset;
4951 first_plt_got_patch = acfg->shared_patches->len;
4952 for (i = 1; i < acfg->plt_offset; ++i) {
4953 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
4955 g_ptr_array_add (acfg->shared_patches, patch_info);
4958 acfg->got_offset += acfg->plt_offset;
4962 * - optimize offsets table.
4963 * - reduce number of exported symbols.
4964 * - emit info for a klass only once.
4965 * - determine when a method uses a GOT slot which is guaranteed to be already
4967 * - clean up and document the code.
4968 * - use String.Empty in class libs.
4971 /* Encode info required to decode shared GOT entries */
4972 buf_size = acfg->shared_patches->len * 64;
4973 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4974 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
4975 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
4976 for (i = 0; i < acfg->shared_patches->len; ++i) {
4977 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
4979 got_info_offsets [i] = p - buf;
4980 /* No need to encode the patch type for non-PLT patches */
4981 if (i >= first_plt_got_patch) {
4982 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
4983 encode_value (ji->type, p, &p);
4985 encode_patch (acfg, ji, p, &p);
4988 g_assert (p - buf <= buf_size);
4990 acfg->stats.got_info_size = p - buf;
4992 /* Emit got_info table */
4993 sprintf (symbol, "got_info");
4994 emit_section_change (acfg, ".text", 1);
4995 emit_global (acfg, symbol, FALSE);
4996 emit_alignment (acfg, 8);
4997 emit_label (acfg, symbol);
4999 emit_bytes (acfg, buf, p - buf);
5001 /* Emit got_info_offsets table */
5002 sprintf (symbol, "got_info_offsets");
5003 emit_section_change (acfg, ".text", 1);
5004 emit_global (acfg, symbol, FALSE);
5005 emit_alignment (acfg, 8);
5006 emit_label (acfg, symbol);
5008 for (i = 0; i < acfg->shared_patches->len; ++i)
5009 emit_int32 (acfg, got_info_offsets [i]);
5011 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
5015 emit_got (MonoAotCompile *acfg)
5019 /* Don't make GOT global so accesses to it don't need relocations */
5020 sprintf (symbol, "got");
5021 emit_section_change (acfg, ".bss", 0);
5022 emit_alignment (acfg, 8);
5023 emit_label (acfg, symbol);
5024 if (acfg->got_offset > 0)
5025 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5029 emit_globals (MonoAotCompile *acfg)
5034 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5036 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5038 opts_str = g_strdup_printf ("%d", acfg->opts);
5039 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
5042 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
5044 if (acfg->aot_opts.bind_to_runtime_version) {
5045 build_info = mono_get_runtime_build_info ();
5046 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5047 g_free (build_info);
5049 emit_string_symbol (acfg, "mono_runtime_version", "");
5053 * Some platforms like the iphone have no working dlsym (). To work around this,
5054 * we create an ELF ctor function which will be invoked by dlopen, and which
5055 * will call a function in the AOT loader to register the symbols used by the
5057 * When static linking, we emit a global which will point to the symbol table.
5059 if (acfg->aot_opts.no_dlsym) {
5063 if (acfg->aot_opts.static_link)
5064 /* Emit a string holding the assembly name */
5065 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5067 /* Emit the names */
5068 for (i = 0; i < acfg->globals->len; ++i) {
5069 char *name = g_ptr_array_index (acfg->globals, i);
5071 sprintf (symbol, "name_%d", i);
5072 emit_section_change (acfg, ".text", 1);
5073 emit_label (acfg, symbol);
5074 emit_string (acfg, name);
5077 /* Emit the globals table */
5078 sprintf (symbol, "globals");
5079 emit_section_change (acfg, ".data", 0);
5080 /* This is not a global, since it is accessed by the init function */
5081 emit_alignment (acfg, 8);
5082 emit_label (acfg, symbol);
5084 for (i = 0; i < acfg->globals->len; ++i) {
5085 char *name = g_ptr_array_index (acfg->globals, i);
5087 sprintf (symbol, "name_%d", i);
5088 emit_pointer (acfg, symbol);
5090 sprintf (symbol, "%s", name);
5091 emit_pointer (acfg, symbol);
5093 /* Null terminate the table */
5094 emit_pointer (acfg, NULL);
5095 emit_pointer (acfg, NULL);
5097 if (acfg->aot_opts.static_link) {
5101 * Emit a global symbol which can be passed by an embedding app to
5102 * mono_aot_register_module ().
5104 #if defined(__MACH__)
5105 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5107 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5110 /* Get rid of characters which cannot occur in symbols */
5112 for (p = symbol; *p; ++p) {
5113 if (!(isalnum (*p) || *p == '_'))
5116 acfg->static_linking_symbol = g_strdup (symbol);
5117 emit_global_inner (acfg, symbol, FALSE);
5118 emit_alignment (acfg, 8);
5119 emit_label (acfg, symbol);
5120 emit_pointer (acfg, "globals");
5122 sprintf (symbol, "init_%s", acfg->image->assembly->aname.name);
5123 emit_section_change (acfg, ".text", 1);
5124 emit_alignment (acfg, 8);
5125 emit_label (acfg, symbol);
5126 #ifdef USE_BIN_WRITER
5127 g_assert_not_reached ();
5130 fprintf (acfg->fp, "leaq globals(%%rip), %%rdi\n");
5131 fprintf (acfg->fp, "call mono_aot_register_globals@PLT\n");
5132 fprintf (acfg->fp, "ret\n");
5133 fprintf (acfg->fp, ".section .ctors,\"aw\",@progbits\n");
5134 emit_alignment (acfg, 8);
5135 emit_pointer (acfg, symbol);
5136 #elif defined(__arm__) && defined(__MACH__)
5138 fprintf (acfg->fp, ".text\n");
5139 fprintf (acfg->fp, ".align 3\n");
5141 fprintf (acfg->fp, "ldr r0, .L5\n");
5142 fprintf (acfg->fp, ".LPIC0:\n");
5143 fprintf (acfg->fp, "add r0, pc, r0\n");
5144 fprintf (acfg->fp, "ldr r0, [r0]\n");
5145 fprintf (acfg->fp, "b _mono_aot_register_globals@PLT\n");
5146 fprintf (acfg->fp, ".align 2\n");
5148 fprintf (acfg->fp, ".L5:\n");
5149 fprintf (acfg->fp, ".long globals_ptr-(.LPIC0+8)\n");
5151 fprintf (acfg->fp, ".data\n");
5152 fprintf (acfg->fp, ".align 2\n");
5153 fprintf (acfg->fp, "globals_ptr:\n");
5154 fprintf (acfg->fp, ".long globals\n");
5156 fprintf (acfg->fp, ".mod_init_func\n");
5157 fprintf (acfg->fp, ".align 2\n");
5158 fprintf (acfg->fp, ".long %s@target1\n", symbol);
5160 #elif defined(__arm__)
5162 * Taken from gcc generated code for:
5164 * void foo () { bar (&i); }
5165 * gcc --shared -fPIC -O2
5167 fprintf (acfg->fp, "ldr r3, .L5\n");
5168 fprintf (acfg->fp, "ldr r0, .L5+4\n");
5169 fprintf (acfg->fp, ".LPIC0:\n");
5170 fprintf (acfg->fp, "add r3, pc, r3\n");
5171 fprintf (acfg->fp, "add r0, r3, r0\n");
5172 fprintf (acfg->fp, "b mono_aot_register_globals(PLT)\n");
5174 fprintf (acfg->fp, ".L5:\n");
5175 fprintf (acfg->fp, ".word _GLOBAL_OFFSET_TABLE_-(.LPIC0+8)\n");
5176 fprintf (acfg->fp, ".word globals(GOTOFF)\n");
5178 fprintf (acfg->fp, ".section .init_array,\"aw\",%%init_array\n");
5179 fprintf (acfg->fp, ".align 2\n");
5180 fprintf (acfg->fp, ".word %s(target1)\n", symbol);
5182 g_assert_not_reached ();
5190 * Emit a structure containing all the information not stored elsewhere.
5193 emit_file_info (MonoAotCompile *acfg)
5197 sprintf (symbol, "mono_aot_file_info");
5198 emit_section_change (acfg, ".data", 0);
5199 emit_alignment (acfg, 8);
5200 emit_label (acfg, symbol);
5201 emit_global (acfg, symbol, FALSE);
5203 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
5204 emit_int32 (acfg, acfg->plt_got_offset_base);
5205 emit_int32 (acfg, acfg->trampoline_got_offset_base);
5206 emit_int32 (acfg, acfg->num_aot_trampolines);
5207 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5208 emit_int32 (acfg, acfg->plt_offset);
5209 emit_pointer (acfg, "got");
5212 /*****************************************/
5213 /* Emitting DWARF debug information */
5214 /*****************************************/
5216 static G_GNUC_UNUSED void
5217 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
5220 guint8 b = value & 0x7f;
5222 if (value != 0) /* more bytes to come */
5224 emit_byte (acfg, b);
5228 static G_GNUC_UNUSED void
5229 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
5232 gboolean negative = (value < 0);
5237 byte = value & 0x7f;
5239 /* the following is unnecessary if the
5240 * implementation of >>= uses an arithmetic rather
5241 * than logical shift for a signed left operand
5245 value |= - (1 <<(size - 7));
5246 /* sign bit of byte is second high order bit (0x40) */
5247 if ((value == 0 && !(byte & 0x40)) ||
5248 (value == -1 && (byte & 0x40)))
5252 emit_byte (acfg, byte);
5256 static G_GNUC_UNUSED void
5257 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
5262 guint8 b = value & 0x7f;
5264 if (value != 0) /* more bytes to come */
5272 static G_GNUC_UNUSED void
5273 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
5276 gboolean negative = (value < 0);
5282 byte = value & 0x7f;
5284 /* the following is unnecessary if the
5285 * implementation of >>= uses an arithmetic rather
5286 * than logical shift for a signed left operand
5290 value |= - (1 <<(size - 7));
5291 /* sign bit of byte is second high order bit (0x40) */
5292 if ((value == 0 && !(byte & 0x40)) ||
5293 (value == -1 && (byte & 0x40)))
5304 emit_dwarf_abbrev (MonoAotCompile *acfg, int code, int tag, gboolean has_child,
5305 int *attrs, int attrs_len)
5309 emit_uleb128 (acfg, code);
5310 emit_uleb128 (acfg, tag);
5311 emit_byte (acfg, has_child);
5313 for (i = 0; i < attrs_len; i++)
5314 emit_uleb128 (acfg, attrs [i]);
5315 emit_uleb128 (acfg, 0);
5316 emit_uleb128 (acfg, 0);
5320 emit_cie (MonoAotCompile *acfg)
5322 #if defined(__x86_64__)
5323 emit_section_change (acfg, ".debug_frame", 0);
5325 emit_alignment (acfg, 8);
5328 emit_symbol_diff (acfg, ".Lcie0_end", ".", -4); /* length */
5329 emit_int32 (acfg, 0xffffffff); /* CIE id */
5330 emit_byte (acfg, 3); /* version */
5331 emit_string (acfg, ""); /* augmention */
5332 emit_sleb128 (acfg, 1); /* code alignment factor */
5334 emit_sleb128 (acfg, -8); /* data alignment factor */
5335 emit_uleb128 (acfg, AMD64_RIP);
5337 g_assert_not_reached ();
5341 emit_byte (acfg, DW_CFA_def_cfa);
5342 emit_uleb128 (acfg, mono_hw_reg_to_dwarf_reg (AMD64_RSP));
5343 emit_uleb128 (acfg, 8); /* offset=8 */
5344 emit_byte (acfg, DW_CFA_offset | AMD64_RIP);
5345 emit_uleb128 (acfg, 1); /* offset=-8 */
5347 g_assert_not_reached ();
5350 emit_alignment (acfg, sizeof (gpointer));
5351 emit_label (acfg, ".Lcie0_end");
5356 emit_pointer_value (MonoAotCompile *acfg, gpointer ptr)
5358 gssize val = (gssize)ptr;
5359 emit_bytes (acfg, (guint8*)&val, sizeof (gpointer));
5363 emit_fde (MonoAotCompile *acfg, int fde_index, char *start_symbol, char *end_symbol,
5364 guint8 *code, guint32 code_size, GSList *unwind_ops)
5366 #if defined(__x86_64__)
5370 guint32 uw_info_len;
5372 emit_section_change (acfg, ".debug_frame", 0);
5374 sprintf (symbol, ".Lfde%d_end", fde_index);
5375 emit_symbol_diff (acfg, symbol, ".", -4); /* length */
5376 emit_int32 (acfg, 0); /* CIE_pointer */
5378 emit_pointer (acfg, start_symbol); /* initial_location */
5379 emit_symbol_diff (acfg, end_symbol, start_symbol, 0); /* address_range */
5380 emit_int32 (acfg, 0);
5382 emit_pointer_value (acfg, code);
5383 emit_int32 (acfg, code_size);
5384 emit_int32 (acfg, 0);
5389 /* Skip the first two ops which are in the CIE */
5393 /* Convert the list of MonoUnwindOps to the format used by DWARF */
5394 uw_info = mono_unwind_ops_encode (l, &uw_info_len);
5395 emit_bytes (acfg, uw_info, uw_info_len);
5398 emit_alignment (acfg, sizeof (gpointer));
5399 sprintf (symbol, ".Lfde%d_end", fde_index);
5400 emit_label (acfg, symbol);
5405 #define AB_COMPILE_UNIT 1
5406 #define AB_SUBPROGRAM 2
5408 #define AB_BASE_TYPE 4
5409 #define AB_STRUCT_TYPE 5
5410 #define AB_DATA_MEMBER 6
5411 #define AB_TYPEDEF 7
5412 #define AB_ENUM_TYPE 8
5413 #define AB_ENUMERATOR 9
5414 #define AB_NAMESPACE 10
5416 static int compile_unit_attr [] = {
5417 DW_AT_producer ,DW_FORM_string,
5418 DW_AT_name ,DW_FORM_string,
5419 DW_AT_comp_dir ,DW_FORM_string,
5420 DW_AT_language ,DW_FORM_data1,
5421 DW_AT_low_pc ,DW_FORM_addr,
5422 DW_AT_high_pc ,DW_FORM_addr,
5425 static int subprogram_attr [] = {
5426 DW_AT_name , DW_FORM_string,
5427 DW_AT_low_pc , DW_FORM_addr,
5428 DW_AT_high_pc , DW_FORM_addr,
5429 DW_AT_frame_base , DW_FORM_block1
5432 static int param_attr [] = {
5433 DW_AT_name, DW_FORM_string,
5434 DW_AT_type, DW_FORM_ref4,
5435 DW_AT_location, DW_FORM_block1
5438 static int base_type_attr [] = {
5439 DW_AT_byte_size, DW_FORM_data1,
5440 DW_AT_encoding, DW_FORM_data1,
5441 DW_AT_name, DW_FORM_string
5444 static int struct_type_attr [] = {
5445 DW_AT_name, DW_FORM_string,
5446 DW_AT_byte_size, DW_FORM_udata,
5449 static int data_member_attr [] = {
5450 DW_AT_name, DW_FORM_string,
5451 DW_AT_type, DW_FORM_ref4,
5452 DW_AT_data_member_location, DW_FORM_block1
5455 static int typedef_attr [] = {
5456 DW_AT_name, DW_FORM_string,
5457 DW_AT_type, DW_FORM_ref4
5460 static int enum_type_attr [] = {
5461 DW_AT_name, DW_FORM_string,
5462 DW_AT_byte_size, DW_FORM_udata,
5463 DW_AT_type, DW_FORM_ref4,
5466 static int enumerator_attr [] = {
5467 DW_AT_name, DW_FORM_string,
5468 DW_AT_const_value, DW_FORM_sdata,
5471 static int namespace_attr [] = {
5472 DW_AT_name, DW_FORM_string,
5475 typedef struct DwarfBasicType {
5476 const char *die_name, *name;
5482 static DwarfBasicType basic_types [] = {
5483 { ".LDIE_I1", "sbyte", MONO_TYPE_I1, 1, DW_ATE_signed },
5484 { ".LDIE_U1", "byte", MONO_TYPE_U1, 1, DW_ATE_unsigned },
5485 { ".LDIE_I2", "short", MONO_TYPE_I2, 2, DW_ATE_signed },
5486 { ".LDIE_U2", "ushort", MONO_TYPE_U2, 2, DW_ATE_unsigned },
5487 { ".LDIE_I4", "int", MONO_TYPE_I4, 4, DW_ATE_signed },
5488 { ".LDIE_U4", "uint", MONO_TYPE_U4, 4, DW_ATE_unsigned },
5489 { ".LDIE_I8", "long", MONO_TYPE_I8, 8, DW_ATE_signed },
5490 { ".LDIE_U8", "ulong", MONO_TYPE_U8, 8, DW_ATE_unsigned },
5491 { ".LDIE_R4", "float", MONO_TYPE_R4, 4, DW_ATE_float },
5492 { ".LDIE_R8", "double", MONO_TYPE_R8, 8, DW_ATE_float },
5493 { ".LDIE_BOOLEAN", "boolean", MONO_TYPE_BOOLEAN, 1, DW_ATE_boolean },
5494 { ".LDIE_STRING", "string", MONO_TYPE_STRING, sizeof (gpointer), DW_ATE_address },
5495 { ".LDIE_OBJECT", "object", MONO_TYPE_OBJECT, sizeof (gpointer), DW_ATE_address },
5496 { ".LDIE_SZARRAY", "object", MONO_TYPE_SZARRAY, sizeof (gpointer), DW_ATE_address },
5500 emit_base_dwarf_info (MonoAotCompile *acfg)
5502 char *s, *build_info;
5505 emit_section_change (acfg, ".debug_abbrev", 0);
5506 emit_dwarf_abbrev (acfg, AB_COMPILE_UNIT, DW_TAG_compile_unit, TRUE,
5507 compile_unit_attr, G_N_ELEMENTS (compile_unit_attr));
5508 emit_dwarf_abbrev (acfg, AB_SUBPROGRAM, DW_TAG_subprogram, TRUE,
5509 subprogram_attr, G_N_ELEMENTS (subprogram_attr));
5510 emit_dwarf_abbrev (acfg, AB_PARAM, DW_TAG_formal_parameter, FALSE,
5511 param_attr, G_N_ELEMENTS (param_attr));
5512 emit_dwarf_abbrev (acfg, AB_BASE_TYPE, DW_TAG_base_type, FALSE,
5513 base_type_attr, G_N_ELEMENTS (base_type_attr));
5514 emit_dwarf_abbrev (acfg, AB_STRUCT_TYPE, DW_TAG_class_type, TRUE,
5515 struct_type_attr, G_N_ELEMENTS (struct_type_attr));
5516 emit_dwarf_abbrev (acfg, AB_DATA_MEMBER, DW_TAG_member, FALSE,
5517 data_member_attr, G_N_ELEMENTS (data_member_attr));
5518 emit_dwarf_abbrev (acfg, AB_TYPEDEF, DW_TAG_typedef, FALSE,
5519 typedef_attr, G_N_ELEMENTS (typedef_attr));
5520 emit_dwarf_abbrev (acfg, AB_ENUM_TYPE, DW_TAG_enumeration_type, TRUE,
5521 enum_type_attr, G_N_ELEMENTS (enum_type_attr));
5522 emit_dwarf_abbrev (acfg, AB_ENUMERATOR, DW_TAG_enumerator, FALSE,
5523 enumerator_attr, G_N_ELEMENTS (enumerator_attr));
5524 emit_dwarf_abbrev (acfg, AB_NAMESPACE, DW_TAG_namespace, TRUE,
5525 namespace_attr, G_N_ELEMENTS (namespace_attr));
5526 emit_byte (acfg, 0);
5528 emit_section_change (acfg, ".debug_info", 0);
5529 emit_label (acfg, ".Ldebug_info_start");
5530 emit_symbol_diff (acfg, ".Ldebug_info_end", ".", -4); /* length */
5531 emit_int16 (acfg, 0x3); /* DWARF version 3 */
5532 emit_int32 (acfg, 0); /* .debug_abbrev offset */
5533 emit_byte (acfg, sizeof (gpointer)); /* address size */
5535 /* Emit this into a separate section so it gets placed at the end */
5536 emit_section_change (acfg, ".debug_info", 1);
5537 emit_int32 (acfg, 0); /* close everything */
5538 emit_label (acfg, ".Ldebug_info_end");
5539 emit_section_change (acfg, ".debug_info", 0);
5541 /* Compilation unit */
5542 emit_uleb128 (acfg, AB_COMPILE_UNIT);
5543 build_info = mono_get_runtime_build_info ();
5544 s = g_strdup_printf ("Mono AOT Compiler %s", build_info);
5545 emit_string (acfg, s);
5546 g_free (build_info);
5548 emit_string (acfg, "JITted code");
5549 emit_string (acfg, "");
5550 emit_byte (acfg, DW_LANG_C);
5551 emit_pointer_value (acfg, 0);
5552 emit_pointer_value (acfg, 0);
5555 for (i = 0; i < G_N_ELEMENTS (basic_types); ++i) {
5556 emit_label (acfg, basic_types [i].die_name);
5557 emit_uleb128 (acfg, AB_BASE_TYPE);
5558 emit_byte (acfg, basic_types [i].size);
5559 emit_byte (acfg, basic_types [i].encoding);
5560 emit_string (acfg, basic_types [i].name);
5566 /* Returns the local symbol pointing to the emitted debug info */
5568 emit_class_dwarf_info (MonoAotCompile *acfg, MonoClass *klass)
5573 MonoClassField *field;
5576 gboolean emit_namespace = FALSE;
5578 // FIXME: Appdomains
5579 if (!acfg->class_to_die)
5580 acfg->class_to_die = g_hash_table_new (NULL, NULL);
5582 die = g_hash_table_lookup (acfg->class_to_die, klass);
5586 if (!((klass->byval_arg.type == MONO_TYPE_CLASS) || klass->enumtype))
5590 * FIXME: gdb can't handle namespaces in languages it doesn't know about.
5593 if (klass->name_space && klass->name_space [0] != '\0')
5594 emit_namespace = TRUE;
5596 if (emit_namespace) {
5597 emit_uleb128 (acfg, AB_NAMESPACE);
5598 emit_string (acfg, klass->name_space);
5601 full_name = g_strdup_printf ("%s%s%s", klass->name_space, klass->name_space ? "." : "", klass->name);
5603 die = g_strdup_printf (".LTDIE_%d", acfg->tdie_index);
5604 emit_label (acfg, die);
5606 if (klass->enumtype) {
5607 int size = mono_class_value_size (mono_class_from_mono_type (klass->enum_basetype), NULL);
5609 emit_uleb128 (acfg, AB_ENUM_TYPE);
5610 emit_string (acfg, full_name);
5611 emit_uleb128 (acfg, size);
5612 for (k = 0; k < G_N_ELEMENTS (basic_types); ++k)
5613 if (basic_types [k].type == klass->enum_basetype->type)
5615 g_assert (k < G_N_ELEMENTS (basic_types));
5616 emit_symbol_diff (acfg, basic_types [k].die_name, ".Ldebug_info_start", 0);
5618 /* Emit enum values */
5620 while ((field = mono_class_get_fields (klass, &iter))) {
5623 MonoTypeEnum def_type;
5625 if (strcmp ("value__", mono_field_get_name (field)) == 0)
5627 if (mono_field_is_deleted (field))
5630 emit_uleb128 (acfg, AB_ENUMERATOR);
5631 emit_string (acfg, mono_field_get_name (field));
5633 p = mono_class_get_field_default_value (field, &def_type);
5634 len = mono_metadata_decode_blob_size (p, &p);
5635 switch (klass->enum_basetype->type) {
5638 emit_sleb128 (acfg, *p);
5640 case MONO_TYPE_CHAR:
5643 emit_sleb128 (acfg, read16 (p));
5647 emit_sleb128 (acfg, read32 (p));
5651 emit_sleb128 (acfg, read64 (p));
5654 g_assert_not_reached ();
5658 emit_uleb128 (acfg, AB_STRUCT_TYPE);
5659 emit_string (acfg, full_name);
5660 emit_uleb128 (acfg, klass->instance_size);
5664 while ((field = mono_class_get_fields (klass, &iter))) {
5668 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
5671 for (k = 0; k < G_N_ELEMENTS (basic_types); ++k)
5672 if (basic_types [k].type == field->type->type)
5674 if (k < G_N_ELEMENTS (basic_types) && field->type->type != MONO_TYPE_SZARRAY && field->type->type != MONO_TYPE_CLASS) {
5675 fdie = basic_types [k].die_name;
5677 emit_uleb128 (acfg, AB_DATA_MEMBER);
5678 emit_string (acfg, field->name);
5679 emit_symbol_diff (acfg, fdie, ".Ldebug_info_start", 0);
5682 *p ++= DW_OP_plus_uconst;
5683 encode_uleb128 (field->offset, p, &p);
5685 emit_byte (acfg, p - buf);
5686 emit_bytes (acfg, buf, p - buf);
5692 emit_uleb128 (acfg, 0x0);
5694 /* Add a typedef, so we can reference the type without a 'struct' in gdb */
5695 emit_uleb128 (acfg, AB_TYPEDEF);
5696 emit_string (acfg, full_name);
5697 emit_symbol_diff (acfg, die, ".Ldebug_info_start", 0);
5700 acfg->tdie_index ++;
5703 if (emit_namespace) {
5705 emit_uleb128 (acfg, 0x0);
5708 g_hash_table_insert (acfg->class_to_die, klass, die);
5713 emit_method_dwarf_info (MonoAotCompile *acfg, MonoMethod *method, char *start_symbol, char *end_symbol, guint8 *code, guint32 code_size, MonoInst **args, GSList *unwind_info)
5716 MonoMethodSignature *sig;
5717 char **names, **tdies;
5720 emit_section_change (acfg, ".debug_info", 0);
5722 sig = mono_method_signature (method);
5724 /* Parameter types */
5725 tdies = g_new0 (char *, sig->param_count + sig->hasthis);
5726 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5729 if (i == 0 && sig->hasthis) {
5730 t = &method->klass->this_arg;
5732 t = sig->params [i - sig->hasthis];
5735 emit_class_dwarf_info (acfg, mono_class_from_mono_type (t));
5739 names = g_new0 (char *, sig->param_count);
5740 mono_method_get_param_names (method, (const char **) names);
5742 emit_uleb128 (acfg, AB_SUBPROGRAM);
5743 name = mono_method_full_name (method, FALSE);
5744 emit_string (acfg, name);
5747 emit_pointer_unaligned (acfg, start_symbol);
5748 emit_pointer_unaligned (acfg, end_symbol);
5750 emit_pointer_value (acfg, code);
5751 emit_pointer_value (acfg, code + code_size);
5754 emit_byte (acfg, 2);
5755 emit_byte (acfg, DW_OP_breg6);
5756 emit_byte (acfg, 16);
5759 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5760 MonoInst *arg = args ? args [i] : NULL;
5765 char pname_buf [128];
5768 if (i == 0 && sig->hasthis) {
5769 t = &mono_defaults.object_class->byval_arg;
5772 t = sig->params [i - sig->hasthis];
5773 pname = names [i - sig->hasthis];
5776 emit_uleb128 (acfg, AB_PARAM);
5778 if (pname[0] == '\0') {
5779 sprintf (pname_buf, "param%d", i - sig->hasthis);
5782 emit_string (acfg, pname);
5784 klass = mono_class_from_mono_type (t);
5785 for (j = 0; j < G_N_ELEMENTS (basic_types); ++j)
5786 if (basic_types [j].type == t->type)
5788 if (j < G_N_ELEMENTS (basic_types))
5789 tdie = basic_types [j].die_name;
5792 case MONO_TYPE_CLASS:
5793 case MONO_TYPE_ARRAY:
5794 tdie = ".LDIE_OBJECT";
5796 case MONO_TYPE_VALUETYPE:
5797 if (klass->enumtype)
5798 tdie = emit_class_dwarf_info (acfg, klass);
5810 if (!arg || arg->flags & MONO_INST_IS_DEAD)
5812 emit_symbol_diff (acfg, tdie, ".Ldebug_info_start", 0);
5814 /* FIXME: This needs a location list, since the args can go from reg->stack */
5815 if (!arg || arg->flags & MONO_INST_IS_DEAD) {
5816 /* gdb treats this as optimized out */
5817 emit_byte (acfg, 0);
5818 } else if (arg->opcode == OP_REGVAR) {
5819 emit_byte (acfg, 1);
5820 emit_byte (acfg, DW_OP_reg0 + mono_hw_reg_to_dwarf_reg (arg->dreg));
5821 } else if (arg->opcode == OP_REGOFFSET) {
5826 *p ++= DW_OP_breg0 + mono_hw_reg_to_dwarf_reg (arg->inst_basereg);
5827 encode_sleb128 (arg->inst_offset, p, &p);
5828 emit_byte (acfg, p - buf);
5829 emit_bytes (acfg, buf, p - buf);
5832 emit_byte (acfg, 1);
5833 emit_byte (acfg, DW_OP_reg0);
5838 /* Subprogram end */
5839 emit_uleb128 (acfg, 0x0);
5841 /* Emit unwind info */
5842 emit_fde (acfg, acfg->fde_index, start_symbol, end_symbol, code, code_size, unwind_info);
5847 emit_dwarf_info (MonoAotCompile *acfg)
5849 #if defined(USE_ELF_WRITER) && defined(__x86_64__)
5851 char symbol [128], symbol2 [128];
5853 emit_base_dwarf_info (acfg);
5855 /* DIEs for methods */
5856 for (i = 0; i < acfg->nmethods; ++i) {
5857 MonoCompile *cfg = acfg->cfgs [i];
5862 sprintf (symbol, ".Lm_%x", i);
5863 sprintf (symbol2, ".Lme_%x", i);
5865 emit_method_dwarf_info (acfg, cfg->method, symbol, symbol2, NULL, 0, cfg->args, cfg->unwind_ops);
5867 #endif /* ELF_WRITER */
5871 acfg_free (MonoAotCompile *acfg)
5875 for (i = 0; i < acfg->nmethods; ++i)
5877 g_free (acfg->cfgs [i]);
5878 g_free (acfg->cfgs);
5879 g_free (acfg->static_linking_symbol);
5880 g_ptr_array_free (acfg->methods, TRUE);
5881 g_ptr_array_free (acfg->shared_patches, TRUE);
5882 g_ptr_array_free (acfg->image_table, TRUE);
5883 g_ptr_array_free (acfg->globals, TRUE);
5884 g_hash_table_destroy (acfg->method_indexes);
5885 g_hash_table_destroy (acfg->plt_offset_to_patch);
5886 g_hash_table_destroy (acfg->patch_to_plt_offset);
5887 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
5888 g_hash_table_destroy (acfg->method_to_cfg);
5889 g_hash_table_destroy (acfg->token_info_hash);
5890 g_hash_table_destroy (acfg->image_hash);
5891 mono_mempool_destroy (acfg->mempool);
5896 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5898 MonoImage *image = ass->image;
5900 int i, res, methods_len;
5901 MonoAotCompile *acfg;
5905 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
5907 acfg = g_new0 (MonoAotCompile, 1);
5908 acfg->methods = g_ptr_array_new ();
5909 acfg->method_indexes = g_hash_table_new (NULL, NULL);
5910 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5911 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5912 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5913 acfg->shared_patches = g_ptr_array_new ();
5914 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5915 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5916 acfg->image_hash = g_hash_table_new (NULL, NULL);
5917 acfg->image_table = g_ptr_array_new ();
5918 acfg->globals = g_ptr_array_new ();
5919 acfg->image = image;
5921 acfg->mempool = mono_mempool_new ();
5922 acfg->extra_methods = g_ptr_array_new ();
5923 InitializeCriticalSection (&acfg->mutex);
5925 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
5926 acfg->aot_opts.write_symbols = TRUE;
5928 mono_aot_parse_options (aot_options, &acfg->aot_opts);
5930 #ifdef USE_BIN_WRITER
5931 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer)
5932 acfg->use_bin_writer = TRUE;
5935 load_profile_files (acfg);
5939 acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 10240 : 0;
5941 acfg->method_index = 1;
5943 /* Collect methods */
5944 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5946 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5948 method = mono_get_method (acfg->image, token, NULL);
5950 /* Load all methods eagerly to skip the slower lazy loading code */
5951 mono_class_setup_methods (method->klass);
5953 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5954 /* Compile the wrapper instead */
5955 /* We do this here instead of add_wrappers () because it is easy to do it here */
5956 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5960 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5961 add_method_with_index (acfg, method, i);
5962 acfg->method_index ++;
5965 add_generic_instances (acfg);
5967 if (acfg->aot_opts.full_aot)
5968 add_wrappers (acfg);
5970 acfg->cfgs_size = acfg->methods->len + 32;
5971 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
5973 /* PLT offset 0 is reserved for the PLT trampoline */
5974 acfg->plt_offset = 1;
5976 /* Compile methods */
5979 if (acfg->aot_opts.nthreads > 0) {
5984 gpointer *user_data;
5985 MonoMethod **methods;
5987 methods_len = acfg->methods->len;
5989 len = acfg->methods->len / acfg->aot_opts.nthreads;
5992 * Partition the list of methods into fragments, and hand it to threads to
5995 threads = g_ptr_array_new ();
5996 /* Make a copy since acfg->methods is modified by compile_method () */
5997 methods = g_new0 (MonoMethod*, methods_len);
5998 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5999 for (i = 0; i < methods_len; ++i)
6000 methods [i] = g_ptr_array_index (acfg->methods, i);
6002 while (i < methods_len) {
6003 frag = g_ptr_array_new ();
6004 for (j = 0; j < len; ++j) {
6005 if (i < methods_len) {
6006 g_ptr_array_add (frag, methods [i]);
6011 user_data = g_new0 (gpointer, 3);
6012 user_data [0] = mono_domain_get ();
6013 user_data [1] = acfg;
6014 user_data [2] = frag;
6016 handle = CreateThread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6017 g_ptr_array_add (threads, handle);
6021 for (i = 0; i < threads->len; ++i) {
6022 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6028 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6029 for (i = methods_len; i < acfg->methods->len; ++i) {
6030 /* This can new methods to acfg->methods */
6031 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6036 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6040 alloc_got_slots (acfg);
6046 emit_extra_methods (acfg);
6048 emit_method_order (acfg);
6050 emit_trampolines (acfg);
6052 emit_class_name_table (acfg);
6054 emit_got_info (acfg);
6056 emit_exception_info (acfg);
6058 emit_class_info (acfg);
6062 emit_image_table (acfg);
6066 emit_file_info (acfg);
6068 emit_globals (acfg);
6070 emit_dwarf_info (acfg);
6072 sprintf (symbol, "mem_end");
6073 emit_section_change (acfg, ".text", 1);
6074 emit_global (acfg, symbol, FALSE);
6075 emit_alignment (acfg, 8);
6076 emit_label (acfg, symbol);
6080 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6082 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)));
6085 res = emit_writeout (acfg);
6091 acfg->stats.link_time = TV_ELAPSED (atv, btv);
6093 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);
6094 if (acfg->stats.genericcount)
6095 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6096 if (acfg->stats.abscount)
6097 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6098 if (acfg->stats.wrappercount)
6099 printf ("%d methods contain wrapper references (%d%%)\n", acfg->stats.wrappercount, acfg->stats.mcount ? (acfg->stats.wrappercount * 100) / acfg->stats.mcount : 100);
6100 if (acfg->stats.lmfcount)
6101 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6102 if (acfg->stats.ocount)
6103 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6104 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);
6105 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6106 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);
6108 printf ("GOT slot distribution:\n");
6109 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6110 if (acfg->stats.got_slot_types [i])
6111 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6119 * Support for emitting debug info for JITted code.
6121 * This works as follows:
6122 * - the runtime writes out an xdb.s file containing DWARF debug info.
6123 * - the user calls a gdb macro
6124 * - the macro compiles and loads this shared library using add-symbol-file.
6126 * This is based on the xdebug functionality in the Kaffe Java VM.
6128 * We emit assembly code instead of using the ELF writer, so we can emit debug info
6129 * incrementally as each method is JITted, and the debugger doesn't have to call
6130 * into the runtime to emit the shared library, which would cause all kinds of
6131 * complications, like threading issues, and the fact that the ELF writer's
6132 * emit_writeout () function cannot be called more than once.
6135 /* The recommended gdb macro is: */
6138 shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
6139 add-symbol-file xdb.so 0
6143 static MonoAotCompile *xdebug_acfg;
6146 * mono_save_xdebug_info:
6148 * Emit debugging info for METHOD into an assembly file which can be assembled
6149 * and loaded into gdb to provide debugging info for JITted code.
6152 mono_save_xdebug_info (MonoMethod *method, guint8 *code, guint32 code_size, MonoInst **args, GSList *unwind_info)
6154 MonoAotCompile *acfg;
6156 // FIXME: Add trampolines too
6159 * One time initialization.
6160 * This should be called during startup so no need for locking.
6163 acfg = g_new0 (MonoAotCompile, 1);
6164 acfg->mempool = mono_mempool_new ();
6165 InitializeCriticalSection (&acfg->mutex);
6166 acfg->aot_opts.asm_only = TRUE;
6167 acfg->aot_opts.outfile = g_strdup ("xdb.s");
6175 /* Emit something so the file has a text segment */
6176 emit_section_change (acfg, ".text", 0);
6177 emit_string (acfg, "");
6179 emit_base_dwarf_info (acfg);
6184 mono_acfg_lock (acfg);
6185 emit_method_dwarf_info (acfg, method, NULL, NULL, code, code_size, args, unwind_info);
6187 mono_acfg_unlock (acfg);
6195 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6201 mono_save_xdebug_info (MonoMethod *method, guint8 *code, guint32 code_size, MonoInst **args, GSList *unwind_info)