2 * aot.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
11 /* Remaining AOT-only work:
12 * - reduce the length of the wrapper names.
13 * - aot IMT tables, so we don't have two kinds of aot code.
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
23 * - every shared method has a MonoGenericJitInfo structure which is only really
24 * used for handling catch clauses with open types, not a very common use case.
28 #include <sys/types.h>
38 #ifndef PLATFORM_WIN32
47 #include <limits.h> /* for PAGESIZE */
52 #include <mono/metadata/tabledefs.h>
53 #include <mono/metadata/class.h>
54 #include <mono/metadata/object.h>
55 #include <mono/metadata/tokentype.h>
56 #include <mono/metadata/appdomain.h>
57 #include <mono/metadata/debug-helpers.h>
58 #include <mono/metadata/assembly.h>
59 #include <mono/metadata/metadata-internals.h>
60 #include <mono/metadata/marshal.h>
61 #include <mono/metadata/gc-internal.h>
62 #include <mono/metadata/method-builder.h>
63 #include <mono/metadata/monitor.h>
64 #include <mono/metadata/mempool-internals.h>
65 #include <mono/metadata/mono-endian.h>
66 #include <mono/metadata/mono-debug.h>
67 #include <mono/metadata/debug-mono-symfile.h>
68 #include <mono/utils/mono-logger.h>
69 #include <mono/utils/mono-compiler.h>
70 #include <mono/utils/mono-time.h>
72 #ifndef PLATFORM_WIN32
73 #include <mono/utils/freebsd-elf32.h>
74 #include <mono/utils/freebsd-elf64.h>
77 #include <mono/utils/freebsd-dwarf.h>
83 #define TV_DECLARE(name) gint64 name
84 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
85 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
88 #define SHARED_EXT ".dll"
89 #elif defined(__ppc__) && defined(__MACH__)
90 #define SHARED_EXT ".dylib"
92 #define SHARED_EXT ".so"
95 #if defined(sparc) || defined(__ppc__) || defined(__powerpc__) || defined(__MACH__)
96 #define AS_STRING_DIRECTIVE ".asciz"
99 #define AS_STRING_DIRECTIVE ".string"
104 // .byte generates 1 byte per expression.
105 // .short generates 2 bytes per expression.
106 // .long generates 4 bytes per expression.
107 // .quad generates 8 bytes per expression.
109 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
110 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
111 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
113 typedef struct MonoAotOptions {
116 gboolean write_symbols;
117 gboolean metadata_only;
118 gboolean bind_to_runtime_version;
121 gboolean static_link;
127 typedef struct MonoAotStats {
128 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
129 int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
130 int methods_without_got_slots, direct_calls, all_calls;
132 int got_slot_types [MONO_PATCH_INFO_NONE];
133 int jit_time, gen_time, link_time;
136 #if defined(__x86_64__) && !defined(PLATFORM_WIN32)
137 #define USE_ELF_WRITER 1
138 #define USE_ELF_RELA 1
141 #if defined(__i386__) && !defined(PLATFORM_WIN32)
142 #define USE_ELF_WRITER 1
145 #if defined(__arm__) && !defined(__MACH__)
146 #define USE_ELF_WRITER 1
149 #if defined(__mips__)
150 #define USE_ELF_WRITER 1
153 #if defined(USE_ELF_WRITER)
154 #define USE_BIN_WRITER 1
157 #ifdef USE_BIN_WRITER
159 typedef struct _BinSymbol BinSymbol;
160 typedef struct _BinReloc BinReloc;
161 typedef struct _BinSection BinSection;
173 typedef struct MonoAotCompile {
176 GHashTable *method_indexes;
179 GHashTable *patch_to_plt_offset;
180 GHashTable *plt_offset_to_patch;
181 GHashTable *patch_to_shared_got_offset;
182 GPtrArray *shared_patches;
183 GHashTable *image_hash;
184 GHashTable *method_to_cfg;
185 GHashTable *token_info_hash;
186 GPtrArray *extra_methods;
187 GPtrArray *image_table;
190 guint32 *plt_got_info_offsets;
191 /* Number of trampolines emitted into the AOT file */
192 guint32 num_aot_trampolines;
193 guint32 got_offset, plt_offset, plt_got_offset_base;
194 /* Number of GOT entries reserved for trampolines */
195 guint32 num_trampoline_got_entries;
196 guint32 trampoline_got_offset_base;
197 MonoAotOptions aot_opts;
200 MonoMemPool *mempool;
203 char *static_linking_symbol;
204 CRITICAL_SECTION mutex;
205 gboolean use_bin_writer;
207 #ifdef USE_BIN_WRITER
209 BinSection *sections;
210 BinSection *cur_section;
211 BinReloc *relocations;
218 int mode; /* emit mode */
219 int col_count; /* bytes emitted per .byte line */
221 GHashTable *class_to_die;
222 int fde_index, tdie_index, line_number_file_index;
225 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
226 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
228 #ifdef HAVE_ARRAY_ELEM_INIT
229 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
230 #define MSGSTRFIELD1(line) str##line
231 static const struct msgstr_t {
232 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
233 #include "patch-info.h"
236 #define PATCH_INFO(a,b) b,
237 #include "patch-info.h"
240 static const gint16 opidx [] = {
241 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
242 #include "patch-info.h"
247 get_patch_name (int info)
249 return (const char*)&opstr + opidx [info];
253 #define PATCH_INFO(a,b) b,
254 static const char* const
255 patch_types [MONO_PATCH_INFO_NUM + 1] = {
256 #include "patch-info.h"
261 get_patch_name (int info)
263 return patch_types [info];
269 emit_global (MonoAotCompile *acfg, const char *name, gboolean func);
272 is_got_patch (MonoJumpInfoType patch_type)
277 static G_GNUC_UNUSED int
278 ilog2(register int value)
281 while (value & ~0xf) count += 4, value >>= 4;
282 while (value) count++, value >>= 1;
286 #ifdef USE_BIN_WRITER
288 typedef struct _BinLabel BinLabel;
299 BinSection *val2_section;
312 gboolean is_function;
331 bin_writer_emit_start (MonoAotCompile *acfg)
333 acfg->labels = g_hash_table_new (g_str_hash, g_str_equal);
337 bin_writer_emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
341 if (acfg->cur_section && acfg->cur_section->subsection == subsection_index
342 && strcmp (acfg->cur_section->name, section_name) == 0)
344 for (section = acfg->sections; section; section = section->next) {
345 if (section->subsection == subsection_index && strcmp (section->name, section_name) == 0) {
346 acfg->cur_section = section;
351 section = g_new0 (BinSection, 1);
352 section->name = g_strdup (section_name);
353 section->subsection = subsection_index;
354 section->next = acfg->sections;
355 acfg->sections = section;
356 acfg->cur_section = section;
361 bin_writer_emit_symbol_inner (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean is_global, gboolean func)
363 BinSymbol *symbol = g_new0 (BinSymbol, 1);
364 symbol->name = g_strdup (name);
366 symbol->end_label = g_strdup (end_label);
367 symbol->is_function = func;
368 symbol->is_global = is_global;
369 symbol->section = acfg->cur_section;
370 /* FIXME: we align after this call... */
371 symbol->offset = symbol->section->cur_offset;
372 symbol->next = acfg->symbols;
373 acfg->symbols = symbol;
377 bin_writer_emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
379 bin_writer_emit_symbol_inner (acfg, name, NULL, TRUE, func);
383 bin_writer_emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
385 bin_writer_emit_symbol_inner (acfg, name, end_label, FALSE, func);
389 bin_writer_emit_label (MonoAotCompile *acfg, const char *name)
391 BinLabel *label = g_new0 (BinLabel, 1);
392 label->name = g_strdup (name);
393 label->section = acfg->cur_section;
394 label->offset = acfg->cur_section->cur_offset;
395 g_hash_table_insert (acfg->labels, label->name, label);
399 bin_writer_emit_ensure_buffer (BinSection *section, int size)
401 int new_offset = section->cur_offset + size;
402 if (new_offset >= section->data_len) {
403 int new_size = section->data_len? section->data_len * 2: 256;
405 while (new_size <= new_offset)
407 data = g_malloc0 (new_size);
408 memcpy (data, section->data, section->data_len);
409 g_free (section->data);
410 section->data = data;
411 section->data_len = new_size;
416 bin_writer_emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
418 bin_writer_emit_ensure_buffer (acfg->cur_section, size);
419 memcpy (acfg->cur_section->data + acfg->cur_section->cur_offset, buf, size);
420 acfg->cur_section->cur_offset += size;
424 bin_writer_emit_string (MonoAotCompile *acfg, const char *value)
426 int size = strlen (value) + 1;
427 bin_writer_emit_bytes (acfg, (const guint8*)value, size);
431 bin_writer_emit_line (MonoAotCompile *acfg)
433 /* Nothing to do in binary writer */
437 bin_writer_emit_alignment (MonoAotCompile *acfg, int size)
439 int offset = acfg->cur_section->cur_offset;
441 offset += (size - 1);
442 offset &= ~(size - 1);
443 add = offset - acfg->cur_section->cur_offset;
445 bin_writer_emit_ensure_buffer (acfg->cur_section, add);
446 acfg->cur_section->cur_offset += add;
451 bin_writer_emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
457 g_assert_not_reached ();
458 reloc = g_new0 (BinReloc, 1);
459 reloc->val1 = g_strdup (target);
460 reloc->section = acfg->cur_section;
461 reloc->section_offset = acfg->cur_section->cur_offset;
462 reloc->next = acfg->relocations;
463 acfg->relocations = reloc;
464 if (strcmp (reloc->section->name, ".data") == 0) {
466 g_print ("reloc: %s at %d\n", target, acfg->cur_section->cur_offset);
468 acfg->cur_section->cur_offset += sizeof (gpointer);
472 bin_writer_emit_pointer (MonoAotCompile *acfg, const char *target)
474 bin_writer_emit_alignment (acfg, sizeof (gpointer));
475 bin_writer_emit_pointer_unaligned (acfg, target);
479 bin_writer_emit_int16 (MonoAotCompile *acfg, int value)
482 bin_writer_emit_ensure_buffer (acfg->cur_section, 2);
483 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
484 acfg->cur_section->cur_offset += 2;
485 /* FIXME: little endian */
487 data [1] = value >> 8;
491 bin_writer_emit_int32 (MonoAotCompile *acfg, int value)
494 bin_writer_emit_ensure_buffer (acfg->cur_section, 4);
495 data = acfg->cur_section->data + acfg->cur_section->cur_offset;
496 acfg->cur_section->cur_offset += 4;
497 /* FIXME: little endian */
499 data [1] = value >> 8;
500 data [2] = value >> 16;
501 data [3] = value >> 24;
505 create_reloc (MonoAotCompile *acfg, const char *end, const char* start, int offset)
508 reloc = mono_mempool_alloc0 (acfg->mempool, sizeof (BinReloc));
509 reloc->val1 = mono_mempool_strdup (acfg->mempool, end);
510 if (strcmp (start, ".") == 0) {
511 reloc->val2_section = acfg->cur_section;
512 reloc->val2_offset = acfg->cur_section->cur_offset;
514 reloc->val2 = mono_mempool_strdup (acfg->mempool, start);
516 reloc->offset = offset;
517 reloc->section = acfg->cur_section;
518 reloc->section_offset = acfg->cur_section->cur_offset;
519 reloc->next = acfg->relocations;
520 acfg->relocations = reloc;
525 bin_writer_emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
527 create_reloc (acfg, end, start, offset);
528 acfg->cur_section->cur_offset += 4;
529 /*if (strcmp (reloc->section->name, ".data") == 0) {
531 g_print ("reloc: %s - %s + %d at %d\n", end, start, offset, acfg->cur_section->cur_offset - 4);
536 * Emit a relocation entry of type RELOC_TYPE against symbol SYMBOL at the current PC.
539 static G_GNUC_UNUSED void
540 bin_writer_emit_reloc (MonoAotCompile *acfg, int reloc_type, const char *symbol, int addend)
542 BinReloc *reloc = create_reloc (acfg, symbol, ".", addend);
543 reloc->reloc_type = reloc_type;
547 bin_writer_emit_zero_bytes (MonoAotCompile *acfg, int num)
549 bin_writer_emit_ensure_buffer (acfg->cur_section, num);
550 acfg->cur_section->cur_offset += num;
553 #ifdef USE_ELF_WRITER
577 /* Relocation types */
578 #define R_ARM_CALL 28
579 #define R_ARM_ALU_PC_G0_NC 59
581 #if SIZEOF_VOID_P == 4
583 typedef Elf32_Ehdr ElfHeader;
584 typedef Elf32_Shdr ElfSectHeader;
585 typedef Elf32_Phdr ElfProgHeader;
586 typedef Elf32_Sym ElfSymbol;
587 typedef Elf32_Rel ElfReloc;
588 typedef Elf32_Rela ElfRelocA;
589 typedef Elf32_Dyn ElfDynamic;
593 typedef Elf64_Ehdr ElfHeader;
594 typedef Elf64_Shdr ElfSectHeader;
595 typedef Elf64_Phdr ElfProgHeader;
596 typedef Elf64_Sym ElfSymbol;
597 typedef Elf64_Rel ElfReloc;
598 typedef Elf64_Rela ElfRelocA;
599 typedef Elf64_Dyn ElfDynamic;
611 static SectInfo section_info [] = {
613 {".hash", SHT_HASH, 4, 2, SIZEOF_VOID_P},
614 {".dynsym", SHT_DYNSYM, sizeof (ElfSymbol), 2, SIZEOF_VOID_P},
615 {".dynstr", SHT_STRTAB, 0, 2, 1},
616 {".rel.dyn", SHT_REL, sizeof (ElfReloc), 2, SIZEOF_VOID_P},
617 {".rela.dyn", SHT_RELA, sizeof (ElfRelocA), 2, SIZEOF_VOID_P},
618 {".text", SHT_PROGBITS, 0, 6, 4096},
619 {".dynamic", SHT_DYNAMIC, sizeof (ElfDynamic), 3, SIZEOF_VOID_P},
620 {".got.plt", SHT_PROGBITS, SIZEOF_VOID_P, 3, SIZEOF_VOID_P},
621 {".data", SHT_PROGBITS, 0, 3, 8},
622 {".bss", SHT_NOBITS, 0, 3, 8},
623 {".debug_frame", SHT_PROGBITS, 0, 0, 8},
624 {".debug_info", SHT_PROGBITS, 0, 0, 1},
625 {".debug_abbrev", SHT_PROGBITS, 0, 0, 1},
626 {".debug_line", SHT_PROGBITS, 0, 0, 1},
627 {".shstrtab", SHT_STRTAB, 0, 0, 1},
628 {".symtab", SHT_SYMTAB, sizeof (ElfSymbol), 0, SIZEOF_VOID_P},
629 {".strtab", SHT_STRTAB, 0, 0, 1}
638 str_table_add (ElfStrTable *table, const char* value)
642 table->data = g_string_new_len ("", 1);
643 table->hash = g_hash_table_new (g_str_hash, g_str_equal);
645 idx = GPOINTER_TO_UINT (g_hash_table_lookup (table->hash, value));
648 idx = table->data->len;
649 g_string_append (table->data, value);
650 g_string_append_c (table->data, 0);
651 g_hash_table_insert (table->hash, (void*)value, GUINT_TO_POINTER (idx));
656 append_subsection (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection *sect, BinSection *add)
658 int offset = sect->cur_offset;
659 /*offset += (sheaders [sect->shidx].sh_addralign - 1);
660 offset &= ~(sheaders [sect->shidx].sh_addralign - 1);*/
663 bin_writer_emit_ensure_buffer (sect, offset);
664 g_print ("section %s aligned to %d from %d\n", sect->name, offset, sect->cur_offset);
665 sect->cur_offset = offset;
667 bin_writer_emit_ensure_buffer (sect, add->cur_offset);
668 memcpy (sect->data + sect->cur_offset, add->data, add->cur_offset);
670 sect->cur_offset += add->cur_offset;
671 add->cur_offset = offset; /* it becomes the offset in the parent section */
672 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);
677 /* merge the subsections */
679 collect_sections (MonoAotCompile *acfg, ElfSectHeader *sheaders, BinSection **out, int num)
681 int i, j, maxs, num_sections;
686 for (sect = acfg->sections; sect; sect = sect->next) {
687 if (sect->subsection == 0) {
688 out [num_sections++] = sect;
689 g_assert (num_sections < num);
691 maxs = MAX (maxs, sect->subsection);
693 for (i = 0; i < num_sections; i++) {
694 for (j = 1; j <= maxs; ++j) {
695 for (sect = acfg->sections; sect; sect = sect->next) {
696 if (sect->subsection == j && strcmp (out [i]->name, sect->name) == 0) {
697 append_subsection (acfg, sheaders, out [i], sect);
706 elf_hash (const unsigned char *name)
708 unsigned long h = 0, g;
710 h = (h << 4) + *name++;
711 if ((g = h & 0xf0000000))
718 #define NUM_BUCKETS 17
721 build_hash (MonoAotCompile *acfg, int num_sections, ElfStrTable *dynstr)
724 int num_symbols = 1 + num_sections + 3;
727 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
728 if (!symbol->is_global)
731 str_table_add (dynstr, symbol->name);
732 /*g_print ("adding sym: %s\n", symbol->name);*/
734 str_table_add (dynstr, "__bss_start");
735 str_table_add (dynstr, "_edata");
736 str_table_add (dynstr, "_end");
738 data = g_new0 (int, num_symbols + 2 + NUM_BUCKETS);
739 data [0] = NUM_BUCKETS;
740 data [1] = num_symbols;
746 get_label_addr (MonoAotCompile *acfg, const char *name)
753 lab = g_hash_table_lookup (acfg->labels, name);
755 g_error ("Undefined label: '%s'.\n", name);
756 section = lab->section;
757 offset = lab->offset;
758 if (section->parent) {
759 value = section->parent->virt_offset + section->cur_offset + offset;
761 value = section->virt_offset + offset;
767 collect_syms (MonoAotCompile *acfg, int *hash, ElfStrTable *strtab, ElfSectHeader *sheaders, int *num_syms)
778 symbols = g_new0 (ElfSymbol, hash [1]);
781 for (symbol = acfg->symbols; symbol; symbol = symbol->next)
784 symbols = g_new0 (ElfSymbol, i + SECT_NUM + 10); /* FIXME */
787 /* the first symbol is undef, all zeroes */
791 for (j = 1; j < SECT_NUM; ++j) {
792 symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
793 symbols [i].st_shndx = j;
794 symbols [i].st_value = sheaders [j].sh_addr;
798 for (section = acfg->sections; section; section = section->next) {
801 symbols [i].st_info = ELF32_ST_INFO (STB_LOCAL, STT_SECTION);
802 if (strcmp (section->name, ".text") == 0) {
803 symbols [i].st_shndx = SECT_TEXT;
804 section->shidx = SECT_TEXT;
805 section->file_offset = 4096;
806 symbols [i].st_value = section->virt_offset;
807 } else if (strcmp (section->name, ".data") == 0) {
808 symbols [i].st_shndx = SECT_DATA;
809 section->shidx = SECT_DATA;
810 section->file_offset = 4096 + 28; /* FIXME */
811 symbols [i].st_value = section->virt_offset;
812 } else if (strcmp (section->name, ".bss") == 0) {
813 symbols [i].st_shndx = SECT_BSS;
814 section->shidx = SECT_BSS;
815 section->file_offset = 4096 + 28 + 8; /* FIXME */
816 symbols [i].st_value = section->virt_offset;
821 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
824 if (!symbol->is_global && hash)
826 symbols [i].st_info = ELF32_ST_INFO (symbol->is_global ? STB_GLOBAL : STB_LOCAL, symbol->is_function? STT_FUNC : STT_OBJECT);
827 symbols [i].st_name = str_table_add (strtab, symbol->name);
828 /*g_print ("sym name %s tabled to %d\n", symbol->name, symbols [i].st_name);*/
829 section = symbol->section;
830 symbols [i].st_shndx = section->parent? section->parent->shidx: section->shidx;
831 lab = g_hash_table_lookup (acfg->labels, symbol->name);
832 offset = lab->offset;
833 if (section->parent) {
834 symbols [i].st_value = section->parent->virt_offset + section->cur_offset + offset;
836 symbols [i].st_value = section->virt_offset + offset;
839 if (symbol->end_label) {
840 BinLabel *elab = g_hash_table_lookup (acfg->labels, symbol->end_label);
842 symbols [i].st_size = elab->offset - lab->offset;
846 /* add special symbols */
847 symbols [i].st_name = str_table_add (strtab, "__bss_start");
848 symbols [i].st_shndx = 0xfff1;
849 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
851 symbols [i].st_name = str_table_add (strtab, "_edata");
852 symbols [i].st_shndx = 0xfff1;
853 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
855 symbols [i].st_name = str_table_add (strtab, "_end");
856 symbols [i].st_shndx = 0xfff1;
857 symbols [i].st_info = ELF32_ST_INFO (STB_GLOBAL, 0);
863 /* add to hash table */
866 chain = hash + 2 + hash [0];
867 for (i = 0; i < hash [1]; ++i) {
869 /*g_print ("checking %d '%s' (sym %d)\n", symbols [i].st_name, strtab->data->str + symbols [i].st_name, i);*/
870 if (!symbols [i].st_name)
872 hashc = elf_hash ((guint8*)strtab->data->str + symbols [i].st_name);
873 slot = hashc % hash [0];
874 /*g_print ("hashing '%s' at slot %d (sym %d)\n", strtab->data->str + symbols [i].st_name, slot, i);*/
876 chain [i] = bucket [slot];
887 reloc_symbols (MonoAotCompile *acfg, ElfSymbol *symbols, ElfSectHeader *sheaders, ElfStrTable *strtab, gboolean dynamic)
895 for (section = acfg->sections; section; section = section->next) {
898 symbols [i].st_value = sheaders [section->shidx].sh_addr;
902 for (i = 1; i < SECT_NUM; ++i) {
903 symbols [i].st_value = sheaders [i].sh_addr;
906 for (symbol = acfg->symbols; symbol; symbol = symbol->next) {
909 if (dynamic && !symbol->is_global)
911 section = symbol->section;
912 lab = g_hash_table_lookup (acfg->labels, symbol->name);
913 offset = lab->offset;
914 if (section->parent) {
915 symbols [i].st_value = sheaders [section->parent->shidx].sh_addr + section->cur_offset + offset;
917 symbols [i].st_value = sheaders [section->shidx].sh_addr + offset;
922 symbols [i].st_value = sheaders [SECT_BSS].sh_addr;
925 symbols [i].st_value = sheaders [SECT_DATA].sh_addr + sheaders [SECT_DATA].sh_size;
928 symbols [i].st_value = sheaders [SECT_BSS].sh_addr + sheaders [SECT_BSS].sh_size;
933 resolve_reloc (MonoAotCompile *acfg, BinReloc *reloc, guint8 **out_data, gsize *out_vaddr, gsize *out_start_val, gsize *out_end_val)
936 gssize end_val, start_val;
939 end_val = get_label_addr (acfg, reloc->val1);
941 start_val = get_label_addr (acfg, reloc->val2);
942 } else if (reloc->val2_section) {
943 start_val = reloc->val2_offset;
944 if (reloc->val2_section->parent)
945 start_val += reloc->val2_section->parent->virt_offset + reloc->val2_section->cur_offset;
947 start_val += reloc->val2_section->virt_offset;
951 end_val = end_val - start_val + reloc->offset;
952 if (reloc->section->parent) {
953 data = reloc->section->parent->data;
954 data += reloc->section->cur_offset;
955 data += reloc->section_offset;
956 vaddr = reloc->section->parent->virt_offset;
957 vaddr += reloc->section->cur_offset;
958 vaddr += reloc->section_offset;
960 data = reloc->section->data;
961 data += reloc->section_offset;
962 vaddr = reloc->section->virt_offset;
963 vaddr += reloc->section_offset;
966 *out_start_val = start_val;
967 *out_end_val = end_val;
975 resolve_relocations (MonoAotCompile *acfg)
979 gsize end_val, start_val;
984 rr = g_new0 (ElfRelocA, acfg->num_relocs);
987 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
988 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
989 /* FIXME: little endian */
991 data [1] = end_val >> 8;
992 data [2] = end_val >> 16;
993 data [3] = end_val >> 24;
995 if (start_val == 0 && reloc->val1 [0] != '.') {
996 rr [i].r_offset = vaddr;
997 rr [i].r_info = R_X86_64_RELATIVE;
998 rr [i].r_addend = end_val;
1000 g_assert (i <= acfg->num_relocs);
1006 #else /* USE_ELF_RELA */
1009 do_reloc (MonoAotCompile *acfg, BinReloc *reloc, guint8 *data, gssize addr)
1013 * We use the official ARM relocation types, but implement only the stuff actually
1014 * needed by the code we generate.
1016 switch (reloc->reloc_type) {
1018 guint32 *code = (guint32*)(gpointer)data;
1019 guint32 ins = *code;
1023 g_assert (data [3] == 0xeb);
1024 if (diff >= 0 && diff <= 33554431) {
1026 ins = (ins & 0xff000000) | diff;
1028 } else if (diff <= 0 && diff >= -33554432) {
1030 ins = (ins & 0xff000000) | (diff & ~0xff000000);
1033 g_assert_not_reached ();
1037 case R_ARM_ALU_PC_G0_NC: {
1038 /* Generated by emit_plt () */
1039 guint8 *code = data;
1042 g_assert (val <= 0xffff);
1043 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
1044 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, (val & 0xFF00) >> 8, 24);
1045 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, val & 0xFF);
1049 g_assert_not_reached ();
1052 g_assert_not_reached ();
1057 resolve_relocations (MonoAotCompile *acfg)
1061 gsize end_val, start_val;
1066 rr = g_new0 (ElfReloc, acfg->num_relocs);
1069 for (reloc = acfg->relocations; reloc; reloc = reloc->next) {
1070 resolve_reloc (acfg, reloc, &data, &vaddr, &start_val, &end_val);
1071 /* FIXME: little endian */
1072 if (reloc->reloc_type) {
1073 /* Must be static */
1074 g_assert (start_val > 0);
1075 do_reloc (acfg, reloc, data, end_val);
1078 data [1] = end_val >> 8;
1079 data [2] = end_val >> 16;
1080 data [3] = end_val >> 24;
1083 if (start_val == 0 && reloc->val1 [0] != '.') {
1084 rr [i].r_offset = vaddr;
1085 rr [i].r_info = R_386_RELATIVE;
1087 g_assert (i <= acfg->num_relocs);
1093 #endif /* USE_ELF_RELA */
1096 bin_writer_emit_writeout (MonoAotCompile *acfg)
1098 char *outfile_name, *tmp_outfile_name;
1101 ElfProgHeader progh [3];
1102 ElfSectHeader secth [SECT_NUM];
1108 ElfStrTable str_table = {NULL, NULL};
1109 ElfStrTable sh_str_table = {NULL, NULL};
1110 ElfStrTable dyn_str_table = {NULL, NULL};
1111 BinSection* all_sections [32];
1112 BinSection* sections [SECT_NUM];
1115 ElfDynamic dynamic [14];
1117 int i, num_sections, file_offset, virt_offset, size, num_symtab;
1120 g_assert (!acfg->aot_opts.asm_only);
1122 if (acfg->aot_opts.outfile)
1123 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1125 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1127 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1129 unlink (tmp_outfile_name);
1130 file = fopen (tmp_outfile_name, "w");
1133 /* Section headers */
1134 memset (§h, 0, sizeof (secth));
1135 memset (&dynamic, 0, sizeof (dynamic));
1136 memset (&header, 0, sizeof (header));
1138 for (i = 1; i < SECT_NUM; ++i) {
1139 secth [i].sh_name = str_table_add (&sh_str_table, section_info [i].name);
1140 secth [i].sh_type = section_info [i].type;
1141 secth [i].sh_addralign = section_info [i].align;
1142 secth [i].sh_flags = section_info [i].flags;
1143 secth [i].sh_entsize = section_info [i].esize;
1145 secth [SECT_DYNSYM].sh_info = SIZEOF_VOID_P == 4 ? 4 : 2;
1146 secth [SECT_SYMTAB].sh_info = SIZEOF_VOID_P == 4 ? 20 : 17;
1147 secth [SECT_HASH].sh_link = SECT_DYNSYM;
1148 secth [SECT_DYNSYM].sh_link = SECT_DYNSTR;
1149 secth [SECT_REL_DYN].sh_link = SECT_DYNSYM;
1150 secth [SECT_RELA_DYN].sh_link = SECT_DYNSYM;
1151 secth [SECT_DYNAMIC].sh_link = SECT_DYNSTR;
1152 secth [SECT_SYMTAB].sh_link = SECT_STRTAB;
1154 num_sections = collect_sections (acfg, secth, all_sections, 8);
1155 hash = build_hash (acfg, num_sections, &dyn_str_table);
1156 num_symtab = hash [1]; /* FIXME */
1157 g_print ("num_sections: %d\n", num_sections);
1158 g_print ("dynsym: %d, dynstr size: %d\n", hash [1], (int)dyn_str_table.data->len);
1159 for (i = 0; i < num_sections; ++i) {
1160 g_print ("section %s, size: %d, %x\n", all_sections [i]->name, all_sections [i]->cur_offset, all_sections [i]->cur_offset);
1163 /* Associate the bin sections with the ELF sections */
1164 memset (sections, 0, sizeof (sections));
1165 for (i = 0; i < num_sections; ++i) {
1166 BinSection *sect = all_sections [i];
1169 for (j = 0; j < SECT_NUM; ++j) {
1170 if (strcmp (sect->name, section_info [j].name) == 0) {
1176 sections [all_sections [i]->shidx] = sect;
1179 /* at this point we know where in the file the first segment sections go */
1180 dynsym = collect_syms (acfg, hash, &dyn_str_table, NULL, NULL);
1181 num_local_syms = hash [1];
1182 symtab = collect_syms (acfg, NULL, &str_table, secth, &num_local_syms);
1184 file_offset = virt_offset = sizeof (header) + sizeof (progh);
1185 secth [SECT_HASH].sh_addr = secth [SECT_HASH].sh_offset = file_offset;
1186 size = sizeof (int) * (2 + hash [0] + hash [1]);
1187 virt_offset = (file_offset += size);
1188 secth [SECT_HASH].sh_size = size;
1189 secth [SECT_DYNSYM].sh_addr = secth [SECT_DYNSYM].sh_offset = file_offset;
1190 size = sizeof (ElfSymbol) * hash [1];
1191 virt_offset = (file_offset += size);
1192 secth [SECT_DYNSYM].sh_size = size;
1193 secth [SECT_DYNSTR].sh_addr = secth [SECT_DYNSTR].sh_offset = file_offset;
1194 size = dyn_str_table.data->len;
1195 virt_offset = (file_offset += size);
1196 secth [SECT_DYNSTR].sh_size = size;
1198 file_offset &= ~(4-1);
1199 secth [SECT_REL_DYN].sh_addr = secth [SECT_REL_DYN].sh_offset = file_offset;
1200 #ifndef USE_ELF_RELA
1201 size = sizeof (ElfReloc) * acfg->num_relocs;
1205 virt_offset = (file_offset += size);
1206 secth [SECT_REL_DYN].sh_size = size;
1207 secth [SECT_RELA_DYN].sh_addr = secth [SECT_RELA_DYN].sh_offset = file_offset;
1209 size = sizeof (ElfRelocA) * acfg->num_relocs;
1213 virt_offset = (file_offset += size);
1214 secth [SECT_RELA_DYN].sh_size = size;
1216 file_offset = ALIGN_TO (file_offset, secth [SECT_TEXT].sh_addralign);
1217 virt_offset = file_offset;
1218 secth [SECT_TEXT].sh_addr = secth [SECT_TEXT].sh_offset = file_offset;
1219 if (sections [SECT_TEXT]) {
1220 size = sections [SECT_TEXT]->cur_offset;
1221 secth [SECT_TEXT].sh_size = size;
1222 file_offset += size;
1225 file_offset = ALIGN_TO (file_offset, secth [SECT_DYNAMIC].sh_addralign);
1226 virt_offset = file_offset;
1228 /* .dynamic, .got.plt, .data, .bss here */
1229 /* Have to increase the virt offset since these go to a separate segment */
1230 virt_offset += PAGESIZE;
1231 secth [SECT_DYNAMIC].sh_addr = virt_offset;
1232 secth [SECT_DYNAMIC].sh_offset = file_offset;
1233 size = sizeof (dynamic);
1234 secth [SECT_DYNAMIC].sh_size = size;
1235 file_offset += size;
1236 virt_offset += size;
1238 file_offset = ALIGN_TO (file_offset, secth [SECT_GOT_PLT].sh_addralign);
1239 virt_offset = ALIGN_TO (virt_offset, secth [SECT_GOT_PLT].sh_addralign);
1240 secth [SECT_GOT_PLT].sh_addr = virt_offset;
1241 secth [SECT_GOT_PLT].sh_offset = file_offset;
1243 secth [SECT_GOT_PLT].sh_size = size;
1244 file_offset += size;
1245 virt_offset += size;
1247 file_offset = ALIGN_TO (file_offset, secth [SECT_DATA].sh_addralign);
1248 virt_offset = ALIGN_TO (virt_offset, secth [SECT_DATA].sh_addralign);
1249 secth [SECT_DATA].sh_addr = virt_offset;
1250 secth [SECT_DATA].sh_offset = file_offset;
1251 if (sections [SECT_DATA]) {
1252 size = sections [SECT_DATA]->cur_offset;
1253 secth [SECT_DATA].sh_size = size;
1254 file_offset += size;
1255 virt_offset += size;
1258 file_offset = ALIGN_TO (file_offset, secth [SECT_BSS].sh_addralign);
1259 virt_offset = ALIGN_TO (virt_offset, secth [SECT_BSS].sh_addralign);
1260 secth [SECT_BSS].sh_addr = virt_offset;
1261 secth [SECT_BSS].sh_offset = file_offset;
1262 if (sections [SECT_BSS]) {
1263 size = sections [SECT_BSS]->cur_offset;
1264 secth [SECT_BSS].sh_size = size;
1267 /* virtual doesn't matter anymore */
1268 file_offset = ALIGN_TO (file_offset, secth [SECT_DEBUG_FRAME].sh_addralign);
1269 secth [SECT_DEBUG_FRAME].sh_offset = file_offset;
1270 if (sections [SECT_DEBUG_FRAME])
1271 size = sections [SECT_DEBUG_FRAME]->cur_offset;
1274 secth [SECT_DEBUG_FRAME].sh_size = size;
1275 file_offset += size;
1277 secth [SECT_DEBUG_INFO].sh_offset = file_offset;
1278 if (sections [SECT_DEBUG_INFO])
1279 size = sections [SECT_DEBUG_INFO]->cur_offset;
1282 secth [SECT_DEBUG_INFO].sh_size = size;
1283 file_offset += size;
1285 secth [SECT_DEBUG_ABBREV].sh_offset = file_offset;
1286 if (sections [SECT_DEBUG_ABBREV])
1287 size = sections [SECT_DEBUG_ABBREV]->cur_offset;
1290 secth [SECT_DEBUG_ABBREV].sh_size = size;
1291 file_offset += size;
1293 secth [SECT_DEBUG_LINE].sh_offset = file_offset;
1294 if (sections [SECT_DEBUG_LINE])
1295 size = sections [SECT_DEBUG_LINE]->cur_offset;
1298 secth [SECT_DEBUG_LINE].sh_size = size;
1299 file_offset += size;
1301 file_offset = ALIGN_TO (file_offset, secth [SECT_SHSTRTAB].sh_addralign);
1302 secth [SECT_SHSTRTAB].sh_offset = file_offset;
1303 size = sh_str_table.data->len;
1304 secth [SECT_SHSTRTAB].sh_size = size;
1305 file_offset += size;
1307 file_offset = ALIGN_TO (file_offset, secth [SECT_SYMTAB].sh_addralign);
1308 secth [SECT_SYMTAB].sh_offset = file_offset;
1309 size = sizeof (ElfSymbol) * num_local_syms;
1310 secth [SECT_SYMTAB].sh_size = size;
1311 file_offset += size;
1313 file_offset = ALIGN_TO (file_offset, secth [SECT_STRTAB].sh_addralign);
1314 secth [SECT_STRTAB].sh_offset = file_offset;
1315 size = str_table.data->len;
1316 secth [SECT_STRTAB].sh_size = size;
1317 file_offset += size;
1320 file_offset &= ~(4-1);
1322 header.e_ident [EI_MAG0] = ELFMAG0;
1323 header.e_ident [EI_MAG1] = ELFMAG1;
1324 header.e_ident [EI_MAG2] = ELFMAG2;
1325 header.e_ident [EI_MAG3] = ELFMAG3;
1326 header.e_ident [EI_CLASS] = SIZEOF_VOID_P == 4 ? ELFCLASS32 : ELFCLASS64;
1327 header.e_ident [EI_DATA] = ELFDATA2LSB;
1328 header.e_ident [EI_VERSION] = EV_CURRENT;
1329 header.e_ident [EI_OSABI] = ELFOSABI_NONE;
1330 header.e_ident [EI_ABIVERSION] = 0;
1331 for (i = EI_PAD; i < EI_NIDENT; ++i)
1332 header.e_ident [i] = 0;
1334 header.e_type = ET_DYN;
1335 #if defined(__i386__)
1336 header.e_machine = EM_386;
1337 #elif defined(__x86_64__)
1338 header.e_machine = EM_X86_64;
1339 #elif defined(__arm__)
1340 header.e_machine = EM_ARM;
1342 g_assert_not_reached ();
1344 header.e_version = 1;
1346 header.e_phoff = sizeof (header);
1347 header.e_ehsize = sizeof (header);
1348 header.e_phentsize = sizeof (ElfProgHeader);
1350 header.e_entry = secth [SECT_TEXT].sh_addr;
1351 header.e_shstrndx = SECT_SHSTRTAB;
1352 header.e_shentsize = sizeof (ElfSectHeader);
1353 header.e_shnum = SECT_NUM;
1354 header.e_shoff = file_offset;
1358 dynamic [i].d_tag = DT_HASH;
1359 dynamic [i].d_un.d_val = secth [SECT_HASH].sh_offset;
1361 dynamic [i].d_tag = DT_STRTAB;
1362 dynamic [i].d_un.d_val = secth [SECT_DYNSTR].sh_offset;
1364 dynamic [i].d_tag = DT_SYMTAB;
1365 dynamic [i].d_un.d_val = secth [SECT_DYNSYM].sh_offset;
1367 dynamic [i].d_tag = DT_STRSZ;
1368 dynamic [i].d_un.d_val = dyn_str_table.data->len;
1370 dynamic [i].d_tag = DT_SYMENT;
1371 dynamic [i].d_un.d_val = sizeof (ElfSymbol);
1374 dynamic [i].d_tag = DT_RELA;
1375 dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_offset;
1377 dynamic [i].d_tag = DT_RELASZ;
1378 dynamic [i].d_un.d_val = secth [SECT_RELA_DYN].sh_size;
1380 dynamic [i].d_tag = DT_RELAENT;
1381 dynamic [i].d_un.d_val = sizeof (ElfRelocA);
1384 dynamic [i].d_tag = DT_REL;
1385 dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_offset;
1387 dynamic [i].d_tag = DT_RELSZ;
1388 dynamic [i].d_un.d_val = secth [SECT_REL_DYN].sh_size;
1390 dynamic [i].d_tag = DT_RELENT;
1391 dynamic [i].d_un.d_val = sizeof (ElfReloc);
1394 dynamic [i].d_tag = DT_RELCOUNT;
1395 dynamic [i].d_un.d_val = acfg->num_relocs;
1398 /* Program header */
1399 memset (&progh, 0, sizeof (progh));
1400 progh [0].p_type = PT_LOAD;
1401 progh [0].p_filesz = progh [0].p_memsz = secth [SECT_DYNAMIC].sh_offset;
1402 progh [0].p_align = 4096;
1403 progh [0].p_flags = 5;
1405 progh [1].p_type = PT_LOAD;
1406 progh [1].p_offset = secth [SECT_DYNAMIC].sh_offset;
1407 progh [1].p_vaddr = progh [1].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1408 progh [1].p_filesz = secth [SECT_BSS].sh_offset - secth [SECT_DYNAMIC].sh_offset;
1409 progh [1].p_memsz = secth [SECT_BSS].sh_addr + secth [SECT_BSS].sh_size - secth [SECT_DYNAMIC].sh_addr;
1410 progh [1].p_align = 4096;
1411 progh [1].p_flags = 6;
1413 progh [2].p_type = PT_DYNAMIC;
1414 progh [2].p_offset = secth [SECT_DYNAMIC].sh_offset;
1415 progh [2].p_vaddr = progh [2].p_paddr = secth [SECT_DYNAMIC].sh_addr;
1416 progh [2].p_filesz = progh [2].p_memsz = secth [SECT_DYNAMIC].sh_size;
1417 progh [2].p_align = SIZEOF_VOID_P;
1418 progh [2].p_flags = 6;
1420 /* Compute the addresses of the bin sections, so relocation can be done */
1421 for (i = 0; i < SECT_NUM; ++i) {
1423 sections [i]->file_offset = secth [i].sh_offset;
1424 sections [i]->virt_offset = secth [i].sh_addr;
1428 reloc_symbols (acfg, dynsym, secth, &dyn_str_table, TRUE);
1429 reloc_symbols (acfg, symtab, secth, &str_table, FALSE);
1430 relocs = resolve_relocations (acfg);
1432 fwrite (&header, sizeof (header), 1, file);
1433 fwrite (&progh, sizeof (progh), 1, file);
1434 fwrite (hash, sizeof (int) * (hash [0] + hash [1] + 2), 1, file);
1435 fwrite (dynsym, sizeof (ElfSymbol) * hash [1], 1, file);
1436 fwrite (dyn_str_table.data->str, dyn_str_table.data->len, 1, file);
1438 fseek (file, secth [SECT_REL_DYN].sh_offset, SEEK_SET);
1439 fwrite (relocs, sizeof (ElfReloc), acfg->num_relocs, file);
1442 fseek (file, secth [SECT_RELA_DYN].sh_offset, SEEK_SET);
1443 fwrite (relocs, secth [SECT_RELA_DYN].sh_size, 1, file);
1446 if (sections [SECT_TEXT]) {
1447 fseek (file, secth [SECT_TEXT].sh_offset, SEEK_SET);
1448 fwrite (sections [SECT_TEXT]->data, sections [SECT_TEXT]->cur_offset, 1, file);
1451 fwrite (dynamic, sizeof (dynamic), 1, file);
1454 size = secth [SECT_DYNAMIC].sh_addr;
1455 fwrite (&size, sizeof (size), 1, file);
1458 if (sections [SECT_DATA]) {
1459 fseek (file, secth [SECT_DATA].sh_offset, SEEK_SET);
1460 fwrite (sections [SECT_DATA]->data, sections [SECT_DATA]->cur_offset, 1, file);
1463 fseek (file, secth [SECT_DEBUG_FRAME].sh_offset, SEEK_SET);
1464 if (sections [SECT_DEBUG_FRAME])
1465 fwrite (sections [SECT_DEBUG_FRAME]->data, sections [SECT_DEBUG_FRAME]->cur_offset, 1, file);
1466 fseek (file, secth [SECT_DEBUG_INFO].sh_offset, SEEK_SET);
1467 if (sections [SECT_DEBUG_INFO])
1468 fwrite (sections [SECT_DEBUG_INFO]->data, sections [SECT_DEBUG_INFO]->cur_offset, 1, file);
1469 fseek (file, secth [SECT_DEBUG_ABBREV].sh_offset, SEEK_SET);
1470 if (sections [SECT_DEBUG_ABBREV])
1471 fwrite (sections [SECT_DEBUG_ABBREV]->data, sections [SECT_DEBUG_ABBREV]->cur_offset, 1, file);
1472 fseek (file, secth [SECT_DEBUG_LINE].sh_offset, SEEK_SET);
1473 if (sections [SECT_DEBUG_LINE])
1474 fwrite (sections [SECT_DEBUG_LINE]->data, sections [SECT_DEBUG_LINE]->cur_offset, 1, file);
1475 fseek (file, secth [SECT_SHSTRTAB].sh_offset, SEEK_SET);
1476 fwrite (sh_str_table.data->str, sh_str_table.data->len, 1, file);
1477 fseek (file, secth [SECT_SYMTAB].sh_offset, SEEK_SET);
1478 fwrite (symtab, sizeof (ElfSymbol) * num_local_syms, 1, file);
1479 fseek (file, secth [SECT_STRTAB].sh_offset, SEEK_SET);
1480 fwrite (str_table.data->str, str_table.data->len, 1, file);
1481 /*g_print ("file_offset %d vs %d\n", file_offset, ftell (file));*/
1482 /*g_assert (file_offset >= ftell (file));*/
1483 fseek (file, file_offset, SEEK_SET);
1484 fwrite (§h, sizeof (secth), 1, file);
1486 rename (tmp_outfile_name, outfile_name);
1488 g_free (tmp_outfile_name);
1489 g_free (outfile_name);
1494 #endif /* USE_ELF_WRITER */
1496 #endif /* USE_BIN_WRITER */
1501 asm_writer_emit_start (MonoAotCompile *acfg)
1503 if (acfg->aot_opts.asm_only) {
1504 if (acfg->aot_opts.outfile)
1505 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1507 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
1508 acfg->fp = fopen (acfg->tmpfname, "w+");
1510 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
1511 acfg->fp = fdopen (i, "w+");
1513 g_assert (acfg->fp);
1517 asm_writer_emit_unset_mode (MonoAotCompile *acfg)
1519 if (acfg->mode == EMIT_NONE)
1521 fprintf (acfg->fp, "\n");
1522 acfg->mode = EMIT_NONE;
1526 asm_writer_emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
1528 asm_writer_emit_unset_mode (acfg);
1529 #if defined(PLATFORM_WIN32)
1530 fprintf (acfg->fp, ".section %s\n", section_name);
1531 #elif defined(__MACH__)
1532 if (strcmp(section_name, ".bss") == 0)
1533 fprintf (acfg->fp, "%s\n", ".data");
1535 fprintf (acfg->fp, "%s\n", section_name);
1536 #elif defined(sparc)
1537 /* For solaris as, GNU as should accept the same */
1538 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1540 if (!strcmp (section_name, ".text") || !strcmp (section_name, ".data") || !strcmp (section_name, ".bss")) {
1541 fprintf (acfg->fp, "%s %d\n", section_name, subsection_index);
1543 fprintf (acfg->fp, ".section \"%s\"\n", section_name);
1544 fprintf (acfg->fp, ".subsection %d\n", subsection_index);
1550 asm_writer_emit_symbol_type (MonoAotCompile *acfg, const char *name, gboolean func)
1559 asm_writer_emit_unset_mode (acfg);
1560 #if defined(__MACH__)
1562 #elif defined(sparc) || defined(__arm__)
1563 fprintf (acfg->fp, "\t.type %s,#%s\n", name, stype);
1564 #elif defined(PLATFORM_WIN32)
1566 #elif defined(__x86_64__) || defined(__i386__)
1567 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1569 fprintf (acfg->fp, "\t.type %s,@%s\n", name, stype);
1574 asm_writer_emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
1576 asm_writer_emit_unset_mode (acfg);
1577 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1578 // mach-o always uses a '_' prefix.
1579 fprintf (acfg->fp, "\t.globl _%s\n", name);
1581 fprintf (acfg->fp, "\t.globl %s\n", name);
1584 asm_writer_emit_symbol_type (acfg, name, func);
1588 asm_writer_emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
1590 asm_writer_emit_unset_mode (acfg);
1592 fprintf (acfg->fp, "\t.local %s\n", name);
1594 asm_writer_emit_symbol_type (acfg, name, func);
1598 asm_writer_emit_label (MonoAotCompile *acfg, const char *name)
1600 asm_writer_emit_unset_mode (acfg);
1601 #if (defined(__ppc__) && defined(__MACH__)) || defined(PLATFORM_WIN32)
1602 // mach-o always uses a '_' prefix.
1603 fprintf (acfg->fp, "_%s:\n", name);
1605 fprintf (acfg->fp, "%s:\n", name);
1608 #if defined(PLATFORM_WIN32)
1609 /* Emit a normal label too */
1610 fprintf (acfg->fp, "%s:\n", name);
1615 asm_writer_emit_string (MonoAotCompile *acfg, const char *value)
1617 asm_writer_emit_unset_mode (acfg);
1618 fprintf (acfg->fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
1622 asm_writer_emit_line (MonoAotCompile *acfg)
1624 asm_writer_emit_unset_mode (acfg);
1625 fprintf (acfg->fp, "\n");
1629 asm_writer_emit_alignment (MonoAotCompile *acfg, int size)
1631 asm_writer_emit_unset_mode (acfg);
1632 #if defined(__arm__)
1633 fprintf (acfg->fp, "\t.align %d\n", ilog2 (size));
1634 #elif defined(__ppc__) && defined(__MACH__)
1635 // the mach-o assembler specifies alignments as powers of 2.
1636 fprintf (acfg->fp, "\t.align %d\t; ilog2\n", ilog2(size));
1637 #elif defined(__powerpc__)
1638 /* ignore on linux/ppc */
1640 fprintf (acfg->fp, "\t.align %d\n", size);
1645 asm_writer_emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
1647 asm_writer_emit_unset_mode (acfg);
1648 asm_writer_emit_alignment (acfg, sizeof (gpointer));
1649 #if defined(__x86_64__)
1650 fprintf (acfg->fp, "\t.quad %s\n", target ? target : "0");
1651 #elif defined(sparc) && SIZEOF_VOID_P == 8
1652 fprintf (acfg->fp, "\t.xword %s\n", target ? target : "0");
1654 fprintf (acfg->fp, "\t.long %s\n", target ? target : "0");
1659 asm_writer_emit_pointer (MonoAotCompile *acfg, const char *target)
1661 asm_writer_emit_unset_mode (acfg);
1662 asm_writer_emit_alignment (acfg, sizeof (gpointer));
1663 asm_writer_emit_pointer_unaligned (acfg, target);
1666 static char *byte_to_str;
1669 asm_writer_emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
1672 if (acfg->mode != EMIT_BYTE) {
1673 acfg->mode = EMIT_BYTE;
1674 acfg->col_count = 0;
1677 if (byte_to_str == NULL) {
1678 byte_to_str = g_new0 (char, 256 * 8);
1679 for (i = 0; i < 256; ++i) {
1680 sprintf (byte_to_str + (i * 8), ",%d", i);
1684 for (i = 0; i < size; ++i, ++acfg->col_count) {
1685 if ((acfg->col_count % 32) == 0)
1686 fprintf (acfg->fp, "\n\t.byte %d", buf [i]);
1688 fputs (byte_to_str + (buf [i] * 8), acfg->fp);
1693 asm_writer_emit_int16 (MonoAotCompile *acfg, int value)
1695 if (acfg->mode != EMIT_WORD) {
1696 acfg->mode = EMIT_WORD;
1697 acfg->col_count = 0;
1699 if ((acfg->col_count++ % 8) == 0)
1700 #if defined(__MACH__)
1701 fprintf (acfg->fp, "\n\t.short ");
1702 #elif defined(__arm__)
1703 /* FIXME: Use .hword on other archs as well */
1704 fprintf (acfg->fp, "\n\t.hword ");
1706 fprintf (acfg->fp, "\n\t.word ");
1709 fprintf (acfg->fp, ", ");
1710 fprintf (acfg->fp, "%d", value);
1714 asm_writer_emit_int32 (MonoAotCompile *acfg, int value)
1716 if (acfg->mode != EMIT_LONG) {
1717 acfg->mode = EMIT_LONG;
1718 acfg->col_count = 0;
1720 if ((acfg->col_count++ % 8) == 0)
1721 fprintf (acfg->fp, "\n\t.long ");
1723 fprintf (acfg->fp, ",");
1724 fprintf (acfg->fp, "%d", value);
1728 asm_writer_emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
1730 if (acfg->mode != EMIT_LONG) {
1731 acfg->mode = EMIT_LONG;
1732 acfg->col_count = 0;
1734 if ((acfg->col_count++ % 8) == 0)
1735 fprintf (acfg->fp, "\n\t.long ");
1737 fprintf (acfg->fp, ",");
1739 fprintf (acfg->fp, "%s - %s + %d", end, start, offset);
1740 else if (offset < 0)
1741 fprintf (acfg->fp, "%s - %s %d", end, start, offset);
1743 fprintf (acfg->fp, "%s - %s", end, start);
1747 asm_writer_emit_zero_bytes (MonoAotCompile *acfg, int num)
1749 asm_writer_emit_unset_mode (acfg);
1750 #if defined(__MACH__)
1751 fprintf (acfg->fp, "\t.space %d\n", num);
1753 fprintf (acfg->fp, "\t.skip %d\n", num);
1758 asm_writer_emit_writeout (MonoAotCompile *acfg)
1760 char *command, *objfile;
1761 char *outfile_name, *tmp_outfile_name;
1765 #if defined(__x86_64__)
1766 #define AS_OPTIONS "--64"
1767 #elif defined(sparc) && SIZEOF_VOID_P == 8
1768 #define AS_OPTIONS "-xarch=v9"
1770 #define AS_OPTIONS ""
1773 if (acfg->aot_opts.asm_only) {
1774 printf ("Output file: '%s'.\n", acfg->tmpfname);
1775 if (acfg->aot_opts.static_link)
1776 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1780 if (acfg->aot_opts.static_link) {
1781 if (acfg->aot_opts.outfile)
1782 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1784 objfile = g_strdup_printf ("%s.o", acfg->image->name);
1786 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
1788 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
1789 printf ("Executing the native assembler: %s\n", command);
1790 if (system (command) != 0) {
1798 if (acfg->aot_opts.static_link) {
1799 printf ("Output file: '%s'.\n", objfile);
1800 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
1805 if (acfg->aot_opts.outfile)
1806 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
1808 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
1810 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1813 command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
1814 #elif defined(__ppc__) && defined(__MACH__)
1815 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
1816 #elif defined(PLATFORM_WIN32)
1817 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
1819 if (acfg->aot_opts.no_dlsym) {
1821 * Need to link using gcc so our ctor function gets called.
1823 command = g_strdup_printf ("gcc -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1825 command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
1828 printf ("Executing the native linker: %s\n", command);
1829 if (system (command) != 0) {
1830 g_free (tmp_outfile_name);
1831 g_free (outfile_name);
1839 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
1840 printf ("Stripping the binary: %s\n", com);
1844 rename (tmp_outfile_name, outfile_name);
1846 g_free (tmp_outfile_name);
1847 g_free (outfile_name);
1850 if (acfg->aot_opts.save_temps)
1851 printf ("Retained input file.\n");
1853 unlink (acfg->tmpfname);
1858 /* EMIT FUNCTIONS */
1860 static void emit_start (MonoAotCompile *acfg)
1862 #ifdef USE_BIN_WRITER
1863 if (acfg->use_bin_writer)
1864 bin_writer_emit_start (acfg);
1866 asm_writer_emit_start (acfg);
1868 asm_writer_emit_start (acfg);
1872 static void emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
1874 #ifdef USE_BIN_WRITER
1875 if (acfg->use_bin_writer)
1876 bin_writer_emit_section_change (acfg, section_name, subsection_index);
1878 asm_writer_emit_section_change (acfg, section_name, subsection_index);
1880 asm_writer_emit_section_change (acfg, section_name, subsection_index);
1884 static void emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
1886 #ifdef USE_BIN_WRITER
1887 if (acfg->use_bin_writer)
1888 bin_writer_emit_global_inner (acfg, name, func);
1890 asm_writer_emit_global_inner (acfg, name, func);
1892 asm_writer_emit_global_inner (acfg, name, func);
1896 static void G_GNUC_UNUSED emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
1898 #ifdef USE_BIN_WRITER
1899 if (acfg->use_bin_writer)
1900 bin_writer_emit_local_symbol (acfg, name, end_label, func);
1902 asm_writer_emit_local_symbol (acfg, name, end_label, func);
1904 asm_writer_emit_local_symbol (acfg, name, end_label, func);
1908 static void emit_label (MonoAotCompile *acfg, const char *name)
1910 #ifdef USE_BIN_WRITER
1911 if (acfg->use_bin_writer)
1912 bin_writer_emit_label (acfg, name);
1914 asm_writer_emit_label (acfg, name);
1916 asm_writer_emit_label (acfg, name);
1920 static void emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
1922 #ifdef USE_BIN_WRITER
1923 if (acfg->use_bin_writer)
1924 bin_writer_emit_bytes (acfg, buf, size);
1926 asm_writer_emit_bytes (acfg, buf, size);
1928 asm_writer_emit_bytes (acfg, buf, size);
1932 static void emit_string (MonoAotCompile *acfg, const char *value)
1934 #ifdef USE_BIN_WRITER
1935 if (acfg->use_bin_writer)
1936 bin_writer_emit_string (acfg, value);
1938 asm_writer_emit_string (acfg, value);
1940 asm_writer_emit_string (acfg, value);
1944 static void emit_line (MonoAotCompile *acfg)
1946 #ifdef USE_BIN_WRITER
1947 if (acfg->use_bin_writer)
1948 bin_writer_emit_line (acfg);
1950 asm_writer_emit_line (acfg);
1952 asm_writer_emit_line (acfg);
1956 static void emit_alignment (MonoAotCompile *acfg, int size)
1958 #ifdef USE_BIN_WRITER
1959 if (acfg->use_bin_writer)
1960 bin_writer_emit_alignment (acfg, size);
1962 asm_writer_emit_alignment (acfg, size);
1964 asm_writer_emit_alignment (acfg, size);
1968 static void emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
1970 #ifdef USE_BIN_WRITER
1971 if (acfg->use_bin_writer)
1972 bin_writer_emit_pointer_unaligned (acfg, target);
1974 asm_writer_emit_pointer_unaligned (acfg, target);
1976 asm_writer_emit_pointer_unaligned (acfg, target);
1980 static void emit_pointer (MonoAotCompile *acfg, const char *target)
1982 #ifdef USE_BIN_WRITER
1983 if (acfg->use_bin_writer)
1984 bin_writer_emit_pointer (acfg, target);
1986 asm_writer_emit_pointer (acfg, target);
1988 asm_writer_emit_pointer (acfg, target);
1992 static void emit_int16 (MonoAotCompile *acfg, int value)
1994 #ifdef USE_BIN_WRITER
1995 if (acfg->use_bin_writer)
1996 bin_writer_emit_int16 (acfg, value);
1998 asm_writer_emit_int16 (acfg, value);
2000 asm_writer_emit_int16 (acfg, value);
2004 static void emit_int32 (MonoAotCompile *acfg, int value)
2006 #ifdef USE_BIN_WRITER
2007 if (acfg->use_bin_writer)
2008 bin_writer_emit_int32 (acfg, value);
2010 asm_writer_emit_int32 (acfg, value);
2012 asm_writer_emit_int32 (acfg, value);
2016 static void emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
2018 #ifdef USE_BIN_WRITER
2019 if (acfg->use_bin_writer)
2020 bin_writer_emit_symbol_diff (acfg, end, start, offset);
2022 asm_writer_emit_symbol_diff (acfg, end, start, offset);
2024 asm_writer_emit_symbol_diff (acfg, end, start, offset);
2028 static void emit_zero_bytes (MonoAotCompile *acfg, int num)
2030 #ifdef USE_BIN_WRITER
2031 if (acfg->use_bin_writer)
2032 bin_writer_emit_zero_bytes (acfg, num);
2034 asm_writer_emit_zero_bytes (acfg, num);
2036 asm_writer_emit_zero_bytes (acfg, num);
2041 emit_writeout (MonoAotCompile *acfg)
2043 #ifdef USE_BIN_WRITER
2044 if (acfg->use_bin_writer)
2045 return bin_writer_emit_writeout (acfg);
2047 return asm_writer_emit_writeout (acfg);
2049 return asm_writer_emit_writeout (acfg);
2054 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
2056 if (acfg->aot_opts.no_dlsym) {
2057 g_ptr_array_add (acfg->globals, g_strdup (name));
2059 emit_global_inner (acfg, name, func);
2064 emit_byte (MonoAotCompile *acfg, guint8 val)
2066 emit_bytes (acfg, &val, 1);
2070 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
2072 emit_section_change (acfg, ".text", 1);
2073 emit_global (acfg, name, FALSE);
2074 emit_label (acfg, name);
2075 emit_string (acfg, value);
2081 mono_get_field_token (MonoClassField *field)
2083 MonoClass *klass = field->parent;
2086 for (i = 0; i < klass->field.count; ++i) {
2087 if (field == &klass->fields [i])
2088 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2091 g_assert_not_reached ();
2096 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2100 //printf ("ENCODE: %d 0x%x.\n", value, value);
2103 * Same encoding as the one used in the metadata, extended to handle values
2104 * greater than 0x1fffffff.
2106 if ((value >= 0) && (value <= 127))
2108 else if ((value >= 0) && (value <= 16383)) {
2109 p [0] = 0x80 | (value >> 8);
2110 p [1] = value & 0xff;
2112 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2113 p [0] = (value >> 24) | 0xc0;
2114 p [1] = (value >> 16) & 0xff;
2115 p [2] = (value >> 8) & 0xff;
2116 p [3] = value & 0xff;
2121 p [1] = (value >> 24) & 0xff;
2122 p [2] = (value >> 16) & 0xff;
2123 p [3] = (value >> 8) & 0xff;
2124 p [4] = value & 0xff;
2132 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2136 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2140 index = g_hash_table_size (cfg->image_hash);
2141 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2142 g_ptr_array_add (cfg->image_table, image);
2148 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2151 MonoClass *k = NULL;
2153 /* FIXME: Search referenced images as well */
2154 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2155 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2160 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
2161 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2167 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2172 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2173 * standard metadata encoding.
2176 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2180 if (klass->generic_class) {
2182 g_assert (klass->type_token);
2184 /* Find a typespec for a class if possible */
2185 token = find_typespec_for_class (acfg, klass);
2187 encode_value (token, p, &p);
2188 encode_value (get_image_index (acfg, acfg->image), p, &p);
2190 MonoClass *gclass = klass->generic_class->container_class;
2191 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2194 /* Encode it ourselves */
2196 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
2197 encode_value (MONO_TYPE_GENERICINST, p, &p);
2198 encode_klass_ref (acfg, gclass, p, &p);
2199 encode_value (inst->type_argc, p, &p);
2200 for (i = 0; i < inst->type_argc; ++i)
2201 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2203 } else if (klass->type_token) {
2204 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2205 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2206 encode_value (get_image_index (acfg, klass->image), p, &p);
2207 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2208 MonoGenericParam *param = klass->byval_arg.data.generic_param;
2211 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
2212 encode_value (klass->byval_arg.type, p, &p);
2214 encode_value (param->num, p, &p);
2216 g_assert (param->owner);
2217 encode_value (param->owner->is_method, p, &p);
2218 if (param->owner->is_method)
2219 encode_method_ref (acfg, param->owner->owner.method, p, &p);
2221 encode_klass_ref (acfg, param->owner->owner.klass, p, &p);
2224 g_assert (klass->rank > 0);
2225 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
2226 encode_value (get_image_index (acfg, klass->image), p, &p);
2227 encode_value (klass->rank, p, &p);
2228 encode_klass_ref (acfg, klass->element_class, p, &p);
2234 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2236 guint32 token = mono_get_field_token (field);
2239 encode_klass_ref (cfg, field->parent, p, &p);
2240 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2241 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2246 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2250 MonoGenericInst *inst;
2252 /* Encode the context */
2253 inst = context->class_inst;
2254 encode_value (inst ? 1 : 0, p, &p);
2256 encode_value (inst->type_argc, p, &p);
2257 for (i = 0; i < inst->type_argc; ++i)
2258 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2260 inst = context->method_inst;
2261 encode_value (inst ? 1 : 0, p, &p);
2263 encode_value (inst->type_argc, p, &p);
2264 for (i = 0; i < inst->type_argc; ++i)
2265 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2271 #define MAX_IMAGE_INDEX 250
2274 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2276 guint32 image_index = get_image_index (acfg, method->klass->image);
2277 guint32 token = method->token;
2278 MonoJumpInfoToken *ji;
2281 g_assert (image_index < MAX_IMAGE_INDEX);
2283 /* Mark methods which can't use aot trampolines because they need the further
2284 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2286 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2287 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2288 encode_value ((252 << 24), p, &p);
2290 if (method->wrapper_type) {
2292 encode_value ((253 << 24), p, &p);
2294 encode_value (method->wrapper_type, p, &p);
2296 switch (method->wrapper_type) {
2297 case MONO_WRAPPER_REMOTING_INVOKE:
2298 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2299 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2302 m = mono_marshal_method_from_wrapper (method);
2304 encode_method_ref (acfg, m, p, &p);
2307 case MONO_WRAPPER_PROXY_ISINST:
2308 case MONO_WRAPPER_LDFLD:
2309 case MONO_WRAPPER_LDFLDA:
2310 case MONO_WRAPPER_STFLD:
2311 case MONO_WRAPPER_ISINST: {
2312 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
2313 encode_klass_ref (acfg, proxy_class, p, &p);
2316 case MONO_WRAPPER_LDFLD_REMOTE:
2317 case MONO_WRAPPER_STFLD_REMOTE:
2319 case MONO_WRAPPER_ALLOC: {
2320 int alloc_type = mono_gc_get_managed_allocator_type (method);
2321 g_assert (alloc_type != -1);
2322 encode_value (alloc_type, p, &p);
2325 case MONO_WRAPPER_STELEMREF:
2327 case MONO_WRAPPER_UNKNOWN:
2328 if (strcmp (method->name, "FastMonitorEnter") == 0)
2329 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
2330 else if (strcmp (method->name, "FastMonitorExit") == 0)
2331 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
2333 g_assert_not_reached ();
2335 case MONO_WRAPPER_STATIC_RGCTX_INVOKE: {
2338 m = mono_marshal_method_from_wrapper (method);
2340 encode_method_ref (acfg, m, p, &p);
2344 g_assert_not_reached ();
2346 } else if (mono_method_signature (method)->is_inflated) {
2348 * This is a generic method, find the original token which referenced it and
2350 * Obtain the token from information recorded by the JIT.
2352 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2354 image_index = get_image_index (acfg, ji->image);
2355 g_assert (image_index < MAX_IMAGE_INDEX);
2359 encode_value ((255 << 24), p, &p);
2360 encode_value (image_index, p, &p);
2361 encode_value (token, p, &p);
2363 MonoMethod *declaring;
2364 MonoGenericContext *context = mono_method_get_context (method);
2366 g_assert (method->is_inflated);
2367 declaring = ((MonoMethodInflated*)method)->declaring;
2370 * This might be a non-generic method of a generic instance, which
2371 * doesn't have a token since the reference is generated by the JIT
2372 * like Nullable:Box/Unbox, or by generic sharing.
2376 encode_value ((254 << 24), p, &p);
2377 /* Encode the klass */
2378 encode_klass_ref (acfg, method->klass, p, &p);
2379 /* Encode the method */
2380 image_index = get_image_index (acfg, method->klass->image);
2381 g_assert (image_index < MAX_IMAGE_INDEX);
2382 g_assert (declaring->token);
2383 token = declaring->token;
2384 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2385 encode_value (image_index, p, &p);
2386 encode_value (token, p, &p);
2387 encode_generic_context (acfg, context, p, &p);
2389 } else if (token == 0) {
2390 /* This might be a method of a constructed type like int[,].Set */
2391 /* Obtain the token from information recorded by the JIT */
2392 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2394 image_index = get_image_index (acfg, ji->image);
2395 g_assert (image_index < MAX_IMAGE_INDEX);
2399 encode_value ((255 << 24), p, &p);
2400 encode_value (image_index, p, &p);
2401 encode_value (token, p, &p);
2403 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2404 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2410 compare_patches (gconstpointer a, gconstpointer b)
2414 i = (*(MonoJumpInfo**)a)->ip.i;
2415 j = (*(MonoJumpInfo**)b)->ip.i;
2429 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2432 static inline gboolean
2433 is_plt_patch (MonoJumpInfo *patch_info)
2435 switch (patch_info->type) {
2436 case MONO_PATCH_INFO_METHOD:
2437 case MONO_PATCH_INFO_INTERNAL_METHOD:
2438 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2439 case MONO_PATCH_INFO_ICALL_ADDR:
2440 case MONO_PATCH_INFO_CLASS_INIT:
2441 case MONO_PATCH_INFO_RGCTX_FETCH:
2442 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2443 case MONO_PATCH_INFO_MONITOR_ENTER:
2444 case MONO_PATCH_INFO_MONITOR_EXIT:
2452 * is_shared_got_patch:
2454 * Return whenever PATCH_INFO refers to a patch which needs a shared GOT
2456 * Keep it in sync with the version in aot-runtime.c.
2458 static inline gboolean
2459 is_shared_got_patch (MonoJumpInfo *patch_info)
2461 switch (patch_info->type) {
2462 case MONO_PATCH_INFO_VTABLE:
2463 case MONO_PATCH_INFO_CLASS:
2464 case MONO_PATCH_INFO_IID:
2465 case MONO_PATCH_INFO_ADJUSTED_IID:
2466 case MONO_PATCH_INFO_FIELD:
2467 case MONO_PATCH_INFO_SFLDA:
2468 case MONO_PATCH_INFO_DECLSEC:
2469 case MONO_PATCH_INFO_LDTOKEN:
2470 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2471 case MONO_PATCH_INFO_RVA:
2472 case MONO_PATCH_INFO_METHODCONST:
2480 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2484 if (is_plt_patch (patch_info)) {
2485 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
2487 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2489 * Allocate a separate PLT slot for each such patch, since some plt
2490 * entries will refer to the method itself, and some will refer to
2499 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2501 res = acfg->plt_offset;
2502 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
2503 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
2504 acfg->plt_offset ++;
2514 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2515 * JI could be found if it exists, otherwise allocates a new one.
2518 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2522 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
2524 return got_offset - 1;
2526 got_offset = acfg->got_offset;
2527 acfg->got_offset ++;
2529 acfg->stats.got_slots ++;
2530 acfg->stats.got_slot_types [ji->type] ++;
2536 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2541 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
2542 got_offset = get_got_offset (acfg, ji);
2543 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
2544 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
2545 g_ptr_array_add (acfg->shared_patches, copy);
2548 return get_got_offset (acfg, ji);
2551 /* Add a method to the list of methods which need to be emitted */
2553 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
2556 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2557 g_ptr_array_add (acfg->methods, method);
2558 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2559 acfg->nmethods = acfg->methods->len + 1;
2564 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2566 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2574 add_method (MonoAotCompile *acfg, MonoMethod *method)
2578 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2582 index = acfg->method_index;
2583 add_method_with_index (acfg, method, index);
2585 /* FIXME: Fix quadratic behavior */
2586 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2588 acfg->method_index ++;
2594 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2598 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2601 add_method (acfg, method);
2602 g_ptr_array_add (acfg->extra_methods, method);
2606 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2608 MonoAotCompile *acfg = user_data;
2609 MonoJitICallInfo *callinfo = value;
2610 MonoMethod *wrapper;
2616 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2617 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2620 add_method (acfg, wrapper);
2624 get_runtime_invoke_sig (MonoMethodSignature *sig)
2626 MonoMethodBuilder *mb;
2629 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2630 m = mono_mb_create_method (mb, sig, 16);
2631 return mono_marshal_get_runtime_invoke (m);
2635 add_wrappers (MonoAotCompile *acfg)
2637 MonoMethod *method, *m;
2638 int i, j, nallocators;
2639 MonoMethodSignature *sig, *csig;
2643 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2644 * so there is only one wrapper of a given type, or inlining their contents into their
2649 * FIXME: This depends on the fact that different wrappers have different
2653 /* FIXME: Collect these automatically */
2655 /* Runtime invoke wrappers */
2657 /* void runtime-invoke () [.cctor] */
2658 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2659 csig->ret = &mono_defaults.void_class->byval_arg;
2660 add_method (acfg, get_runtime_invoke_sig (csig));
2662 /* void runtime-invoke () [Finalize] */
2663 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2665 csig->ret = &mono_defaults.void_class->byval_arg;
2666 add_method (acfg, get_runtime_invoke_sig (csig));
2668 /* void runtime-invoke (string) [exception ctor] */
2669 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2671 csig->ret = &mono_defaults.void_class->byval_arg;
2672 csig->params [0] = &mono_defaults.string_class->byval_arg;
2673 add_method (acfg, get_runtime_invoke_sig (csig));
2675 /* void runtime-invoke (string, string) [exception ctor] */
2676 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2678 csig->ret = &mono_defaults.void_class->byval_arg;
2679 csig->params [0] = &mono_defaults.string_class->byval_arg;
2680 csig->params [1] = &mono_defaults.string_class->byval_arg;
2681 add_method (acfg, get_runtime_invoke_sig (csig));
2683 /* string runtime-invoke () [Exception.ToString ()] */
2684 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2686 csig->ret = &mono_defaults.string_class->byval_arg;
2687 add_method (acfg, get_runtime_invoke_sig (csig));
2689 /* void runtime-invoke (string, Exception) [exception ctor] */
2690 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2692 csig->ret = &mono_defaults.void_class->byval_arg;
2693 csig->params [0] = &mono_defaults.string_class->byval_arg;
2694 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2695 add_method (acfg, get_runtime_invoke_sig (csig));
2697 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2698 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2700 csig->ret = &(mono_class_from_name (
2701 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2702 csig->params [0] = &mono_defaults.string_class->byval_arg;
2703 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2704 add_method (acfg, get_runtime_invoke_sig (csig));
2706 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2708 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2709 gboolean skip = FALSE;
2711 method = mono_get_method (acfg->image, token, NULL);
2713 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2714 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2715 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2718 if (method->is_generic || method->klass->generic_container)
2721 /* Skip methods which can not be handled by get_runtime_invoke () */
2722 sig = mono_method_signature (method);
2723 if ((sig->ret->type == MONO_TYPE_PTR) ||
2724 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2727 for (j = 0; j < sig->param_count; j++) {
2728 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2733 add_method (acfg, mono_marshal_get_runtime_invoke (method));
2736 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2737 MonoMethodDesc *desc;
2738 MonoMethod *orig_method;
2740 /* JIT icall wrappers */
2741 /* FIXME: locking */
2742 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2744 /* Managed Allocators */
2745 nallocators = mono_gc_get_managed_allocator_types ();
2746 for (i = 0; i < nallocators; ++i) {
2747 m = mono_gc_get_managed_allocator_by_type (i);
2749 add_method (acfg, m);
2753 add_method (acfg, mono_marshal_get_stelemref ());
2755 /* Monitor Enter/Exit */
2756 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2757 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2758 g_assert (orig_method);
2759 mono_method_desc_free (desc);
2760 method = mono_monitor_get_fast_path (orig_method);
2762 add_method (acfg, method);
2764 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2765 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2766 g_assert (orig_method);
2767 mono_method_desc_free (desc);
2768 method = mono_monitor_get_fast_path (orig_method);
2770 add_method (acfg, method);
2773 /* remoting-invoke wrappers */
2774 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2775 MonoMethodSignature *sig;
2777 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2778 method = mono_get_method (acfg->image, token, NULL);
2780 sig = mono_method_signature (method);
2782 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
2783 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2784 m = mono_marshal_get_remoting_invoke_with_check (method);
2786 add_method (acfg, m);
2790 /* delegate-invoke wrappers */
2791 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2794 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2795 klass = mono_class_get (acfg->image, token);
2797 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2798 method = mono_get_delegate_invoke (klass);
2800 m = mono_marshal_get_delegate_invoke (method, NULL);
2802 add_method (acfg, m);
2804 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2805 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2807 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2808 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2812 /* Synchronized wrappers */
2813 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2814 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2815 method = mono_get_method (acfg->image, token, NULL);
2817 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
2818 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2822 /* static rgctx wrappers */
2823 /* FIXME: Each wrapper belongs to a given instantiation of a generic method */
2824 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2825 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2826 method = mono_get_method (acfg->image, token, NULL);
2828 if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
2829 (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
2830 mono_class_generic_sharing_enabled (method->klass) &&
2831 mono_method_is_generic_sharable_impl (method, FALSE)) {
2832 m = mono_marshal_get_static_rgctx_invoke (method);
2833 add_method (acfg, m);
2838 /* pinvoke wrappers */
2839 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2841 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2843 method = mono_get_method (acfg->image, token, NULL);
2845 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
2846 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2851 has_type_vars (MonoClass *klass)
2853 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2856 return has_type_vars (klass->element_class);
2857 if (klass->generic_class) {
2858 MonoGenericContext *context = &klass->generic_class->context;
2859 if (context->class_inst) {
2862 for (i = 0; i < context->class_inst->type_argc; ++i)
2863 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2871 method_has_type_vars (MonoMethod *method)
2873 if (has_type_vars (method->klass))
2876 if (method->is_inflated) {
2877 MonoGenericContext *context = mono_method_get_context (method);
2878 if (context->method_inst) {
2881 for (i = 0; i < context->method_inst->type_argc; ++i)
2882 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2890 * add_generic_instances:
2892 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2895 add_generic_instances (MonoAotCompile *acfg)
2900 MonoGenericContext *context;
2902 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2903 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2904 method = mono_get_method (acfg->image, token, NULL);
2906 context = mono_method_get_context (method);
2907 if (context && ((context->class_inst && context->class_inst->is_open) ||
2908 (context->method_inst && context->method_inst->is_open)))
2911 if (method->klass->image != acfg->image)
2914 if (mono_method_is_generic_sharable_impl (method, FALSE))
2918 add_extra_method (acfg, method);
2921 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2925 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2927 klass = mono_class_get (acfg->image, token);
2930 mono_class_init (klass);
2932 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2935 if (has_type_vars (klass))
2938 if (!klass->generic_class && !klass->rank)
2942 * Add rgctx wrappers for cctors since those are called by the runtime, so
2943 * there is no methodspec for them. This is needed even for shared classes,
2944 * since rgctx wrappers belong to inflated methods.
2946 method = mono_class_get_cctor (klass);
2948 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
2951 while ((method = mono_class_get_methods (klass, &iter))) {
2952 if (mono_method_is_generic_sharable_impl (method, FALSE))
2956 if (method->is_generic)
2961 * FIXME: Instances which are referenced by these methods are not added,
2962 * for example Array.Resize<int> for List<int>.Add ().
2964 add_extra_method (acfg, method);
2970 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2972 int i, pindex, start_index, method_index;
2974 MonoJumpInfo *patch_info;
2975 MonoMethodHeader *header;
2976 gboolean skip, direct_call;
2978 char direct_call_target [128];
2981 header = mono_method_get_header (method);
2983 method_index = get_method_index (acfg, method);
2986 /* Collect and sort relocations */
2987 patches = g_ptr_array_new ();
2988 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2989 g_ptr_array_add (patches, patch_info);
2990 g_ptr_array_sort (patches, compare_patches);
2993 for (i = 0; i < code_len; i++) {
2995 for (pindex = start_index; pindex < patches->len; ++pindex) {
2996 patch_info = g_ptr_array_index (patches, pindex);
2997 if (patch_info->ip.i >= i)
3001 #ifdef MONO_ARCH_AOT_SUPPORTED
3003 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3004 start_index = pindex;
3006 switch (patch_info->type) {
3007 case MONO_PATCH_INFO_NONE:
3009 case MONO_PATCH_INFO_GOT_OFFSET: {
3010 guint32 offset = mono_arch_get_patch_offset (code + i);
3011 emit_bytes (acfg, code + i, offset);
3012 emit_symbol_diff (acfg, "got", ".", offset);
3014 i += offset + 4 - 1;
3019 if (!is_got_patch (patch_info->type))
3023 * If this patch is a call, try emitting a direct call instead of
3024 * through a PLT entry. This is possible if the called method is in
3025 * the same assembly and requires no initialization.
3027 direct_call = FALSE;
3028 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
3029 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3031 gboolean direct_callable = TRUE;
3033 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3034 direct_callable = FALSE;
3035 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
3036 // FIXME: Maybe call the wrapper directly ?
3037 direct_callable = FALSE;
3038 if (direct_callable) {
3039 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3041 sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
3042 patch_info->type = MONO_PATCH_INFO_NONE;
3043 acfg->stats.direct_calls ++;
3047 acfg->stats.all_calls ++;
3050 if (!got_only && !direct_call) {
3051 int plt_offset = get_plt_offset (acfg, patch_info);
3052 if (plt_offset != -1) {
3053 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3055 sprintf (direct_call_target, ".Lp_%d", plt_offset);
3057 /* Nullify the patch */
3058 patch_info->type = MONO_PATCH_INFO_NONE;
3063 #if defined(__i386__) || defined(__x86_64__)
3064 g_assert (code [i] == 0xe8);
3065 /* Need to make sure this is exactly 5 bytes long */
3066 emit_byte (acfg, '\xe8');
3067 emit_symbol_diff (acfg, direct_call_target, ".", -4);
3069 #elif defined(__arm__)
3070 #ifdef USE_BIN_WRITER
3078 bin_writer_emit_reloc (acfg, R_ARM_CALL, direct_call_target, -8);
3079 emit_bytes (acfg, buf, 4);
3082 asm_writer_emit_unset_mode (acfg);
3083 fprintf (acfg->fp, "bl %s\n", direct_call_target);
3087 g_assert_not_reached ();
3090 got_slot = get_got_offset (acfg, patch_info);
3092 emit_bytes (acfg, code + i, mono_arch_get_patch_offset (code + i));
3094 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
3095 #elif defined(__i386__)
3096 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
3097 #elif defined(__arm__)
3098 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
3100 g_assert_not_reached ();
3103 i += mono_arch_get_patch_offset (code + i) + 4 - 1;
3109 #endif /* MONO_ARCH_AOT_SUPPORTED */
3112 /* Find next patch */
3114 for (pindex = start_index; pindex < patches->len; ++pindex) {
3115 patch_info = g_ptr_array_index (patches, pindex);
3116 if (patch_info->ip.i >= i)
3120 /* Try to emit multiple bytes at once */
3121 if (pindex < patches->len && patch_info->ip.i > i) {
3122 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3123 i = patch_info->ip.i - 1;
3125 emit_bytes (acfg, code + i, 1);
3132 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3138 int func_alignment = 16;
3139 MonoMethodHeader *header;
3141 method = cfg->orig_method;
3142 code = cfg->native_code;
3143 header = mono_method_get_header (method);
3145 method_index = get_method_index (acfg, method);
3147 /* Make the labels local */
3148 sprintf (symbol, ".Lm_%x", method_index);
3150 emit_alignment (acfg, func_alignment);
3151 emit_label (acfg, symbol);
3153 if (acfg->aot_opts.write_symbols && acfg->use_bin_writer) {
3155 /* Emit a local symbol into the symbol table */
3156 full_name = mono_method_full_name (method, TRUE);
3157 sprintf (symbol, ".Lme_%x", method_index);
3158 emit_local_symbol (acfg, full_name, symbol, TRUE);
3159 emit_label (acfg, full_name);
3163 if (cfg->verbose_level > 0)
3164 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3166 acfg->stats.code_size += cfg->code_len;
3168 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3170 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3174 sprintf (symbol, ".Lme_%x", method_index);
3175 emit_label (acfg, symbol);
3181 * Encode PATCH_INFO into its disk representation.
3184 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3188 switch (patch_info->type) {
3189 case MONO_PATCH_INFO_NONE:
3191 case MONO_PATCH_INFO_IMAGE:
3192 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3194 case MONO_PATCH_INFO_METHOD_REL:
3195 encode_value ((gint)patch_info->data.offset, p, &p);
3197 case MONO_PATCH_INFO_SWITCH: {
3198 gpointer *table = (gpointer *)patch_info->data.table->table;
3201 encode_value (patch_info->data.table->table_size, p, &p);
3202 for (k = 0; k < patch_info->data.table->table_size; k++)
3203 encode_value ((int)(gssize)table [k], p, &p);
3206 case MONO_PATCH_INFO_METHODCONST:
3207 case MONO_PATCH_INFO_METHOD:
3208 case MONO_PATCH_INFO_METHOD_JUMP:
3209 case MONO_PATCH_INFO_ICALL_ADDR:
3210 case MONO_PATCH_INFO_METHOD_RGCTX:
3211 encode_method_ref (acfg, patch_info->data.method, p, &p);
3213 case MONO_PATCH_INFO_INTERNAL_METHOD:
3214 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3215 guint32 len = strlen (patch_info->data.name);
3217 encode_value (len, p, &p);
3219 memcpy (p, patch_info->data.name, len);
3224 case MONO_PATCH_INFO_LDSTR: {
3225 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3226 guint32 token = patch_info->data.token->token;
3227 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3228 encode_value (image_index, p, &p);
3229 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3232 case MONO_PATCH_INFO_RVA:
3233 case MONO_PATCH_INFO_DECLSEC:
3234 case MONO_PATCH_INFO_LDTOKEN:
3235 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3236 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3237 encode_value (patch_info->data.token->token, p, &p);
3238 encode_value (patch_info->data.token->has_context, p, &p);
3239 if (patch_info->data.token->has_context)
3240 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3242 case MONO_PATCH_INFO_EXC_NAME: {
3243 MonoClass *ex_class;
3246 mono_class_from_name (mono_defaults.exception_class->image,
3247 "System", patch_info->data.target);
3248 g_assert (ex_class);
3249 encode_klass_ref (acfg, ex_class, p, &p);
3252 case MONO_PATCH_INFO_R4:
3253 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3255 case MONO_PATCH_INFO_R8:
3256 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3257 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
3259 case MONO_PATCH_INFO_VTABLE:
3260 case MONO_PATCH_INFO_CLASS:
3261 case MONO_PATCH_INFO_IID:
3262 case MONO_PATCH_INFO_ADJUSTED_IID:
3263 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3265 case MONO_PATCH_INFO_CLASS_INIT:
3266 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3267 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3269 case MONO_PATCH_INFO_FIELD:
3270 case MONO_PATCH_INFO_SFLDA:
3271 encode_field_info (acfg, patch_info->data.field, p, &p);
3273 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3275 case MONO_PATCH_INFO_RGCTX_FETCH: {
3276 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3278 encode_method_ref (acfg, entry->method, p, &p);
3279 encode_value (entry->in_mrgctx, p, &p);
3280 encode_value (entry->info_type, p, &p);
3281 encode_value (entry->data->type, p, &p);
3282 encode_patch (acfg, entry->data, p, &p);
3285 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3286 case MONO_PATCH_INFO_MONITOR_ENTER:
3287 case MONO_PATCH_INFO_MONITOR_EXIT:
3290 g_warning ("unable to handle jump info %d", patch_info->type);
3291 g_assert_not_reached ();
3298 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3301 guint32 last_offset, j, pindex;
3302 MonoJumpInfo *patch_info;
3304 encode_value (n_patches, p, &p);
3307 encode_value (first_got_offset, p, &p);
3309 /* First encode the type+position table */
3312 for (pindex = 0; pindex < patches->len; ++pindex) {
3314 patch_info = g_ptr_array_index (patches, pindex);
3316 if (patch_info->type == MONO_PATCH_INFO_NONE)
3321 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
3322 offset = patch_info->ip.i - last_offset;
3323 last_offset = patch_info->ip.i;
3325 /* Only the type is needed */
3326 *p = patch_info->type;
3330 /* Then encode the other info */
3331 for (pindex = 0; pindex < patches->len; ++pindex) {
3332 patch_info = g_ptr_array_index (patches, pindex);
3334 if (is_shared_got_patch (patch_info)) {
3335 guint32 offset = get_got_offset (acfg, patch_info);
3336 encode_value (offset, p, &p);
3338 encode_patch (acfg, patch_info, p, &p);
3346 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3350 int pindex, buf_size, n_patches;
3354 MonoJumpInfo *patch_info;
3355 MonoMethodHeader *header;
3356 guint32 method_index;
3358 guint32 first_got_offset;
3360 method = cfg->orig_method;
3361 code = cfg->native_code;
3362 header = mono_method_get_header (method);
3364 method_index = get_method_index (acfg, method);
3366 /* Make the labels local */
3367 sprintf (symbol, ".Lm_%x_p", method_index);
3369 /* Sort relocations */
3370 patches = g_ptr_array_new ();
3371 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3372 g_ptr_array_add (patches, patch_info);
3373 g_ptr_array_sort (patches, compare_patches);
3375 first_got_offset = acfg->cfgs [method_index]->got_offset;
3377 /**********************/
3378 /* Encode method info */
3379 /**********************/
3381 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3382 p = buf = g_malloc (buf_size);
3384 if (mono_class_get_cctor (method->klass))
3385 encode_klass_ref (acfg, method->klass, p, &p);
3387 /* Not needed when loading the method */
3388 encode_value (0, p, &p);
3391 if (cfg->opt & MONO_OPT_SHARED) {
3392 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3393 for (l = cfg->ldstr_list; l; l = l->next) {
3394 encode_value ((long)l->data, p, &p);
3398 /* Used only in shared mode */
3399 g_assert (!cfg->ldstr_list);
3402 for (pindex = 0; pindex < patches->len; ++pindex) {
3403 patch_info = g_ptr_array_index (patches, pindex);
3405 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3406 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3407 patch_info->type = MONO_PATCH_INFO_NONE;
3412 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3413 /* Stored in a GOT slot initialized at module load time */
3414 patch_info->type = MONO_PATCH_INFO_NONE;
3418 if (is_plt_patch (patch_info)) {
3419 /* Calls are made through the PLT */
3420 patch_info->type = MONO_PATCH_INFO_NONE;
3428 g_assert (cfg->has_got_slots);
3430 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3432 acfg->stats.info_size += p - buf;
3434 /* Emit method info */
3436 emit_label (acfg, symbol);
3438 g_assert (p - buf < buf_size);
3439 emit_bytes (acfg, buf, p - buf);
3444 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3447 int k, buf_size, method_index;
3448 guint32 debug_info_size;
3451 MonoMethodHeader *header;
3452 guint8 *p, *buf, *debug_info;
3453 MonoJitInfo *jinfo = cfg->jit_info;
3455 gboolean use_unwind_ops = FALSE;
3457 method = cfg->orig_method;
3458 code = cfg->native_code;
3459 header = mono_method_get_header (method);
3461 method_index = get_method_index (acfg, method);
3463 /* Make the labels local */
3464 sprintf (symbol, ".Le_%x_p", method_index);
3466 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3468 buf_size = header->num_clauses * 256 + debug_info_size + 256;
3469 p = buf = g_malloc (buf_size);
3471 #if defined(__x86_64__)
3472 use_unwind_ops = cfg->unwind_ops != NULL;
3475 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0);
3477 encode_value (jinfo->code_size, p, &p);
3478 encode_value (flags, p, &p);
3480 if (use_unwind_ops) {
3481 guint32 encoded_len;
3485 * This is a duplicate of the data in the .debug_frame section, but that
3486 * section cannot be accessed using the dl interface.
3488 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3489 encode_value (encoded_len, p, &p);
3490 memcpy (p, encoded, encoded_len);
3494 encode_value (jinfo->used_regs, p, &p);
3497 /* Exception table */
3498 if (header->num_clauses) {
3499 for (k = 0; k < header->num_clauses; ++k) {
3500 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3502 encode_value (ei->exvar_offset, p, &p);
3504 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
3505 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3507 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3508 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3509 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3513 if (jinfo->has_generic_jit_info) {
3514 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3516 encode_value (gi->has_this ? 1 : 0, p, &p);
3517 encode_value (gi->this_reg, p, &p);
3518 encode_value (gi->this_offset, p, &p);
3521 * Need to encode jinfo->method too, since it is not equal to 'method'
3522 * when using generic sharing.
3524 encode_method_ref (acfg, jinfo->method, p, &p);
3527 g_assert (debug_info_size < buf_size);
3529 encode_value (debug_info_size, p, &p);
3530 if (debug_info_size) {
3531 memcpy (p, debug_info, debug_info_size);
3532 p += debug_info_size;
3533 g_free (debug_info);
3536 acfg->stats.ex_info_size += p - buf;
3540 emit_label (acfg, symbol);
3542 g_assert (p - buf < buf_size);
3543 emit_bytes (acfg, buf, p - buf);
3548 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3550 MonoClass *klass = mono_class_get (acfg->image, token);
3554 gboolean no_special_static, cant_encode;
3555 gpointer iter = NULL;
3557 buf_size = 10240 + (klass->vtable_size * 16);
3558 p = buf = g_malloc (buf_size);
3562 mono_class_init (klass);
3564 mono_class_get_nested_types (klass, &iter);
3565 g_assert (klass->nested_classes_inited);
3567 mono_class_setup_vtable (klass);
3570 * Emit all the information which is required for creating vtables so
3571 * the runtime does not need to create the MonoMethod structures which
3572 * take up a lot of space.
3575 no_special_static = !mono_class_has_special_static_fields (klass);
3577 /* Check whenever we have enough info to encode the vtable */
3578 cant_encode = FALSE;
3579 for (i = 0; i < klass->vtable_size; ++i) {
3580 MonoMethod *cm = klass->vtable [i];
3582 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3586 if (klass->generic_container || cant_encode) {
3587 encode_value (-1, p, &p);
3589 encode_value (klass->vtable_size, p, &p);
3590 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);
3591 if (klass->has_cctor)
3592 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3593 if (klass->has_finalize)
3594 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3596 encode_value (klass->instance_size, p, &p);
3597 encode_value (mono_class_data_size (klass), p, &p);
3598 encode_value (klass->packing_size, p, &p);
3599 encode_value (klass->min_align, p, &p);
3601 for (i = 0; i < klass->vtable_size; ++i) {
3602 MonoMethod *cm = klass->vtable [i];
3605 encode_method_ref (acfg, cm, p, &p);
3607 encode_value (0, p, &p);
3611 acfg->stats.class_info_size += p - buf;
3614 sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
3615 emit_label (acfg, symbol);
3617 g_assert (p - buf < buf_size);
3618 emit_bytes (acfg, buf, p - buf);
3623 * Calls made from AOTed code are routed through a table of jumps similar to the
3624 * ELF PLT (Program Linkage Table). The differences are the following:
3625 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3626 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3627 * jumps. This means the jumps need to be patched when the address of the callee is
3628 * known. Initially the PLT entries jump to code which transfers control to the
3629 * AOT runtime through the first PLT entry.
3632 emit_plt (MonoAotCompile *acfg)
3638 sprintf (symbol, "plt");
3640 emit_section_change (acfg, ".text", 0);
3641 emit_global (acfg, symbol, TRUE);
3643 /* This section will be made read-write by the AOT loader */
3644 emit_alignment (acfg, PAGESIZE);
3646 emit_alignment (acfg, 16);
3648 emit_label (acfg, symbol);
3650 for (i = 0; i < acfg->plt_offset; ++i) {
3652 #if defined(__arm__)
3657 sprintf (label, ".Lp_%d", i);
3658 emit_label (acfg, label);
3661 * The first plt entry is used to transfer code to the AOT loader.
3664 #if defined(__i386__)
3666 /* It is filled up during loading by the AOT loader. */
3667 emit_zero_bytes (acfg, 16);
3669 /* Need to make sure this is 9 bytes long */
3670 emit_byte (acfg, '\xe9');
3671 emit_symbol_diff (acfg, "plt", ".", -4);
3672 emit_int32 (acfg, acfg->plt_got_info_offsets [i]);
3674 #elif defined(__x86_64__)
3676 * We can't emit jumps because they are 32 bits only so they can't be patched.
3677 * So we make indirect calls through GOT entries which are patched by the AOT
3678 * loader to point to .Lpd entries.
3679 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
3681 /* jmpq *<offset>(%rip) */
3682 emit_byte (acfg, '\xff');
3683 emit_byte (acfg, '\x25');
3684 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + i) * sizeof (gpointer)) -4);
3685 /* Used by mono_aot_get_plt_info_offset */
3686 emit_int32 (acfg, acfg->plt_got_info_offsets [i]);
3687 #elif defined(__arm__)
3689 * - optimize OP_AOTCONST implementation
3690 * - optimize the PLT entries
3691 * - optimize SWITCH AOT implementation
3692 * - implement IMT support
3695 #ifdef USE_BIN_WRITER
3696 /* We only emit 1 relocation since we implement it ourselves anyway */
3697 bin_writer_emit_reloc (acfg, R_ARM_ALU_PC_G0_NC, "got", ((acfg->plt_got_offset_base + i) * sizeof (gpointer)) - 8);
3698 /* FIXME: A 2 instruction encoding is sufficient in most cases */
3699 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
3700 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
3701 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
3702 emit_bytes (acfg, buf, code - buf);
3703 /* FIXME: Get rid of this */
3704 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + i) * sizeof (gpointer)));
3705 /* Used by mono_aot_get_plt_info_offset */
3706 emit_int32 (acfg, acfg->plt_got_info_offsets [i]);
3708 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
3709 ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
3710 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
3711 emit_bytes (acfg, buf, code - buf);
3712 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + i) * sizeof (gpointer)));
3713 /* Used by mono_aot_get_plt_info_offset */
3714 emit_int32 (acfg, acfg->plt_got_info_offsets [i]);
3718 g_assert_not_reached ();
3722 sprintf (symbol, "plt_end");
3723 emit_global (acfg, symbol, TRUE);
3724 emit_label (acfg, symbol);
3727 static G_GNUC_UNUSED void
3728 emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code,
3729 guint32 code_size, int got_offset, MonoJumpInfo *ji)
3733 MonoJumpInfo *patch_info;
3739 sprintf (symbol, "%s", name);
3741 emit_section_change (acfg, ".text", 0);
3742 emit_global (acfg, symbol, TRUE);
3743 emit_alignment (acfg, 16);
3744 emit_label (acfg, symbol);
3747 * The code should access everything through the GOT, so we pass
3750 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3754 /* Sort relocations */
3755 patches = g_ptr_array_new ();
3756 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3757 g_ptr_array_add (patches, patch_info);
3758 g_ptr_array_sort (patches, compare_patches);
3760 buf_size = patches->len * 128 + 128;
3761 buf = g_malloc (buf_size);
3764 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3765 g_assert (p - buf < buf_size);
3767 sprintf (symbol, "%s_p", name);
3769 emit_section_change (acfg, ".text", 0);
3770 emit_global (acfg, symbol, FALSE);
3771 emit_label (acfg, symbol);
3773 emit_bytes (acfg, buf, p - buf);
3777 * When running in aot-only mode, we can't create trampolines at runtime, so we create
3778 * a few, and save them in the AOT file. Normal trampolines embed their argument as a
3779 * literal inside the trampoline code, we can't do that here, so instead we embed an offset
3780 * which needs to be added to the trampoline address to get the address of the GOT slot
3781 * which contains the argument value.
3782 * The generated trampolines jump to the generic trampolines using another GOT slot, which
3783 * will be setup by the AOT loader to point to the generic trampoline code of the given
3787 emit_trampolines (MonoAotCompile *acfg)
3791 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3798 if (!acfg->aot_opts.full_aot)
3801 g_assert (acfg->image->assembly);
3803 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3804 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3805 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3807 * Emit the generic trampolines.
3809 * We could save some code by treating the generic trampolines as a wrapper
3810 * method, but that approach has its own complexities, so we choose the simpler
3813 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3814 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, TRUE);
3816 /* Emit trampoline code */
3818 sprintf (symbol, "generic_trampoline_%d", tramp_type);
3820 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3823 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3824 emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL);
3825 #if defined(__x86_64__) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3826 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3827 emit_named_code (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji);
3828 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3829 emit_named_code (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji);
3832 /* Emit the exception related code pieces */
3833 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3834 emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji);
3835 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3836 emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji);
3837 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3838 emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji);
3839 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3840 emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji);
3841 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3842 emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji);
3843 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3844 emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji);
3846 #if defined(__x86_64__) || defined(__arm__)
3847 for (i = 0; i < 128; ++i) {
3850 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3851 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3852 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3853 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3855 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3856 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3857 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3858 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji);
3864 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3868 /* Reserve some entries at the end of the GOT for our use */
3869 acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
3871 sprintf (symbol, "trampolines");
3873 emit_section_change (acfg, ".text", 0);
3874 emit_global (acfg, symbol, TRUE);
3875 emit_alignment (acfg, 16);
3876 emit_label (acfg, symbol);
3878 for (i = 0; i < acfg->num_aot_trampolines; ++i) {
3879 offset = acfg->got_offset + (i * 2);
3882 * The trampolines created here are variations of the specific
3883 * trampolines created in mono_arch_create_specific_trampoline (). The
3885 * - the generic trampoline address is taken from a got slot.
3886 * - the offset of the got slot where the trampoline argument is stored
3887 * is embedded in the instruction stream, and the generic trampoline
3888 * can load the argument by loading the offset, adding it to the
3889 * address of the trampoline to get the address of the got slot, and
3890 * loading the argument from the there.
3892 #if defined(__x86_64__)
3893 /* This should be exactly 16 bytes long */
3894 /* It should work together with the generic trampoline code in tramp-amd64.c */
3895 /* call *<offset>(%rip) */
3896 emit_byte (acfg, '\x41');
3897 emit_byte (acfg, '\xff');
3898 emit_byte (acfg, '\x15');
3899 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
3900 /* This should be relative to the start of the trampoline */
3901 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
3902 emit_zero_bytes (acfg, 5);
3903 #elif defined(__arm__)
3907 /* Generate the trampoline code */
3908 /* This should be exactly 28 bytes long */
3911 ARM_PUSH (code, 0x5fff);
3912 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
3913 /* Load the value from the GOT */
3914 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
3916 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
3917 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
3919 g_assert (code - buf == 20);
3922 emit_bytes (acfg, buf, code - buf);
3923 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
3924 emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
3927 g_assert_not_reached ();
3932 /* Unbox trampolines */
3934 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3936 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3938 char call_target [256];
3940 method = mono_get_method (acfg->image, token, NULL);
3942 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3943 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
3946 sprintf (symbol, "unbox_trampoline_%d", i);
3948 emit_section_change (acfg, ".text", 0);
3949 emit_global (acfg, symbol, TRUE);
3950 emit_label (acfg, symbol);
3952 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
3954 #if defined(__x86_64__)
3959 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (cfg->orig_method), cfg->generic_sharing_context, NULL);
3961 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
3963 emit_bytes (acfg, buf, code - buf);
3965 emit_byte (acfg, '\xe9');
3966 emit_symbol_diff (acfg, call_target, ".", -4);
3968 #elif defined(__arm__)
3975 if (MONO_TYPE_ISSTRUCT (mono_method_signature (cfg->orig_method)->ret))
3978 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
3980 emit_bytes (acfg, buf, code - buf);
3981 /* jump to method */
3982 #if defined(USE_BIN_WRITER)
3984 g_assert_not_reached ();
3986 fprintf (acfg->fp, "\n\tb %s\n", call_target);
3990 g_assert_not_reached ();
3994 acfg->trampoline_got_offset_base = acfg->got_offset;
3996 acfg->got_offset += acfg->num_trampoline_got_entries;
4000 str_begins_with (const char *str1, const char *str2)
4002 int len = strlen (str2);
4003 return strncmp (str1, str2, len) == 0;
4007 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4009 gchar **args, **ptr;
4011 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4012 for (ptr = args; ptr && *ptr; ptr ++) {
4013 const char *arg = *ptr;
4015 if (str_begins_with (arg, "outfile=")) {
4016 opts->outfile = g_strdup (arg + strlen ("outfile="));
4017 } else if (str_begins_with (arg, "save-temps")) {
4018 opts->save_temps = TRUE;
4019 } else if (str_begins_with (arg, "keep-temps")) {
4020 opts->save_temps = TRUE;
4021 } else if (str_begins_with (arg, "write-symbols")) {
4022 opts->write_symbols = TRUE;
4023 } else if (str_begins_with (arg, "metadata-only")) {
4024 opts->metadata_only = TRUE;
4025 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4026 opts->bind_to_runtime_version = TRUE;
4027 } else if (str_begins_with (arg, "full")) {
4028 opts->full_aot = TRUE;
4030 * The no-dlsym option is only useful on the iphone, and even there,
4031 * do to other limitations of the dynamic linker, it doesn't seem to
4032 * work. So disable it for now so we don't have to support it.
4035 } else if (str_begins_with (arg, "no-dlsym")) {
4036 opts->no_dlsym = TRUE;
4038 } else if (str_begins_with (arg, "threads=")) {
4039 opts->nthreads = atoi (arg + strlen ("threads="));
4040 } else if (str_begins_with (arg, "static")) {
4041 opts->static_link = TRUE;
4042 opts->no_dlsym = TRUE;
4043 } else if (str_begins_with (arg, "asmonly")) {
4044 opts->asm_only = TRUE;
4045 } else if (str_begins_with (arg, "asmwriter")) {
4046 opts->asm_writer = TRUE;
4048 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4057 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4059 MonoMethod *method = (MonoMethod*)key;
4060 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4061 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4062 MonoAotCompile *acfg = user_data;
4064 new_ji->image = ji->image;
4065 new_ji->token = ji->token;
4066 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4070 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4072 switch (patch_info->type) {
4073 case MONO_PATCH_INFO_METHOD:
4074 case MONO_PATCH_INFO_METHODCONST:
4075 if (patch_info->data.method->wrapper_type) {
4076 switch (patch_info->data.method->wrapper_type) {
4077 case MONO_WRAPPER_NONE:
4078 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4079 case MONO_WRAPPER_XDOMAIN_INVOKE:
4080 case MONO_WRAPPER_STFLD:
4081 case MONO_WRAPPER_LDFLD:
4082 case MONO_WRAPPER_LDFLDA:
4083 case MONO_WRAPPER_LDFLD_REMOTE:
4084 case MONO_WRAPPER_STFLD_REMOTE:
4085 case MONO_WRAPPER_STELEMREF:
4086 case MONO_WRAPPER_ISINST:
4087 case MONO_WRAPPER_PROXY_ISINST:
4088 case MONO_WRAPPER_ALLOC:
4089 case MONO_WRAPPER_REMOTING_INVOKE:
4090 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
4091 case MONO_WRAPPER_UNKNOWN:
4094 //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));
4098 if (!patch_info->data.method->token) {
4099 /* The method is part of a constructed type like Int[,].Set (). */
4100 if (!g_hash_table_lookup (acfg->token_info_hash, patch_info->data.method))
4105 case MONO_PATCH_INFO_VTABLE:
4106 case MONO_PATCH_INFO_CLASS_INIT:
4107 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4108 case MONO_PATCH_INFO_CLASS:
4109 case MONO_PATCH_INFO_IID:
4110 case MONO_PATCH_INFO_ADJUSTED_IID:
4111 if (!patch_info->data.klass->type_token)
4112 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))
4115 case MONO_PATCH_INFO_RGCTX_FETCH: {
4116 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4118 if (!can_encode_patch (acfg, entry->data))
4132 * AOT compile a given method.
4133 * This function might be called by multiple threads, so it must be thread-safe.
4136 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4139 MonoJumpInfo *patch_info;
4142 MonoMethod *wrapped;
4144 if (acfg->aot_opts.metadata_only)
4147 mono_acfg_lock (acfg);
4148 index = get_method_index (acfg, method);
4149 mono_acfg_unlock (acfg);
4151 /* fixme: maybe we can also precompile wrapper methods */
4152 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4153 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4154 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4155 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4159 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4162 wrapped = mono_marshal_method_from_wrapper (method);
4163 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4164 // FIXME: The wrapper should be generic too, but it is not
4167 InterlockedIncrement (&acfg->stats.mcount);
4170 if (method->is_generic || method->klass->generic_container) {
4171 InterlockedIncrement (&acfg->stats.genericcount);
4176 if (acfg->aot_opts.full_aot)
4177 mono_use_imt = FALSE;
4180 * Since these methods are the only ones which are compiled with
4181 * AOT support, and they are not used by runtime startup/shutdown code,
4182 * the runtime will not see AOT methods during AOT compilation,so it
4183 * does not need to support them by creating a fake GOT etc.
4185 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4186 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4187 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4188 InterlockedIncrement (&acfg->stats.genericcount);
4191 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4192 /* Let the exception happen at runtime */
4196 if (cfg->disable_aot) {
4197 //printf ("Skip (other): %s\n", mono_method_full_name (method, TRUE));
4198 InterlockedIncrement (&acfg->stats.ocount);
4199 mono_destroy_compile (cfg);
4203 /* Nullify patches which need no aot processing */
4204 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4205 switch (patch_info->type) {
4206 case MONO_PATCH_INFO_LABEL:
4207 case MONO_PATCH_INFO_BB:
4208 patch_info->type = MONO_PATCH_INFO_NONE;
4215 /* Collect method->token associations from the cfg */
4216 mono_acfg_lock (acfg);
4217 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4218 mono_acfg_unlock (acfg);
4221 * Check for absolute addresses.
4224 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4225 switch (patch_info->type) {
4226 case MONO_PATCH_INFO_ABS:
4227 /* unable to handle this */
4228 //printf ("Skip (abs addr): %s %d\n", mono_method_full_name (method, TRUE), patch_info->type);
4237 InterlockedIncrement (&acfg->stats.abscount);
4238 mono_destroy_compile (cfg);
4242 /* Lock for the rest of the code */
4243 mono_acfg_lock (acfg);
4246 * Check for methods/klasses we can't encode.
4249 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4250 if (!can_encode_patch (acfg, patch_info))
4255 acfg->stats.ocount++;
4256 mono_destroy_compile (cfg);
4257 mono_acfg_unlock (acfg);
4261 /* Adds generic instances referenced by this method */
4262 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4263 switch (patch_info->type) {
4264 case MONO_PATCH_INFO_METHOD: {
4265 MonoMethod *m = patch_info->data.method;
4266 if (m->is_inflated) {
4267 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4268 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4269 !method_has_type_vars (m))
4270 add_extra_method (acfg, m);
4279 /* Determine whenever the method has GOT slots */
4280 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4281 switch (patch_info->type) {
4282 case MONO_PATCH_INFO_GOT_OFFSET:
4283 case MONO_PATCH_INFO_NONE:
4285 case MONO_PATCH_INFO_IMAGE:
4286 /* The assembly is stored in GOT slot 0 */
4287 if (patch_info->data.image != acfg->image)
4288 cfg->has_got_slots = TRUE;
4291 if (!is_plt_patch (patch_info))
4292 cfg->has_got_slots = TRUE;
4297 if (!cfg->has_got_slots)
4298 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4300 /* Make a copy of the patch info which is in the mempool */
4302 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4304 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4305 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4308 patches = new_patch_info;
4310 patches_end->next = new_patch_info;
4311 patches_end = new_patch_info;
4313 cfg->patch_info = patches;
4315 /* Make a copy of the unwind info */
4317 GSList *l, *unwind_ops;
4321 for (l = cfg->unwind_ops; l; l = l->next) {
4322 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4323 memcpy (op, l->data, sizeof (MonoUnwindOp));
4324 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4326 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4328 /* Make a copy of the argument/local info */
4330 MonoInst **args, **locals;
4331 MonoMethodSignature *sig;
4332 MonoMethodHeader *header;
4335 sig = mono_method_signature (method);
4336 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4337 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4338 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4339 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4343 header = mono_method_get_header (method);
4344 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4345 for (i = 0; i < header->num_locals; ++i) {
4346 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4347 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4349 cfg->locals = locals;
4352 /* Free some fields used by cfg to conserve memory */
4353 mono_mempool_destroy (cfg->mempool);
4354 cfg->mempool = NULL;
4355 g_free (cfg->varinfo);
4356 cfg->varinfo = NULL;
4360 mono_regstate_free (cfg->rs);
4364 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4366 while (index >= acfg->cfgs_size) {
4367 MonoCompile **new_cfgs;
4370 new_size = acfg->cfgs_size * 2;
4371 new_cfgs = g_new0 (MonoCompile*, new_size);
4372 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4373 g_free (acfg->cfgs);
4374 acfg->cfgs = new_cfgs;
4375 acfg->cfgs_size = new_size;
4377 acfg->cfgs [index] = cfg;
4379 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4381 if (cfg->orig_method->wrapper_type)
4382 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4384 mono_acfg_unlock (acfg);
4386 InterlockedIncrement (&acfg->stats.ccount);
4390 compile_thread_main (gpointer *user_data)
4392 MonoDomain *domain = user_data [0];
4393 MonoAotCompile *acfg = user_data [1];
4394 GPtrArray *methods = user_data [2];
4397 mono_thread_attach (domain);
4399 for (i = 0; i < methods->len; ++i)
4400 compile_method (acfg, g_ptr_array_index (methods, i));
4404 load_profile_files (MonoAotCompile *acfg)
4408 int file_index, res, method_index, i;
4415 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);
4417 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4422 infile = fopen (tmp, "r");
4425 printf ("Using profile data file '%s'\n", tmp);
4430 res = fscanf (infile, "%32s\n", ver);
4431 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
4432 printf ("Profile file has wrong version or invalid.\n");
4438 res = fscanf (infile, "%d\n", &token);
4442 method_index = mono_metadata_token_index (token) - 1;
4444 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
4445 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4450 /* Add missing methods */
4452 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4453 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4454 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4456 unordered = g_list_reverse (unordered);
4457 if (acfg->method_order)
4458 g_list_last (acfg->method_order)->next = unordered;
4460 acfg->method_order = unordered;
4466 * Collect all patches which have shared GOT entries and alloc entries for them. The
4467 * rest will get entries allocated during emit_code ().
4470 alloc_got_slots (MonoAotCompile *acfg)
4476 /* Slot 0 is reserved for the address of the current assembly */
4477 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
4478 ji->type = MONO_PATCH_INFO_IMAGE;
4479 ji->data.image = acfg->image;
4481 get_shared_got_offset (acfg, ji);
4483 for (l = acfg->method_order; l != NULL; l = l->next) {
4484 i = GPOINTER_TO_UINT (l->data);
4486 if (acfg->cfgs [i]) {
4487 MonoCompile *cfg = acfg->cfgs [i];
4489 for (ji = cfg->patch_info; ji; ji = ji->next) {
4490 if (is_shared_got_patch (ji))
4491 get_shared_got_offset (acfg, ji);
4498 emit_code (MonoAotCompile *acfg)
4504 sprintf (symbol, "methods");
4505 emit_section_change (acfg, ".text", 0);
4506 emit_global (acfg, symbol, TRUE);
4507 emit_alignment (acfg, 8);
4508 emit_label (acfg, symbol);
4511 * Emit some padding so the local symbol for the first method doesn't have the
4512 * same address as 'methods'.
4514 emit_zero_bytes (acfg, 16);
4516 for (l = acfg->method_order; l != NULL; l = l->next) {
4517 i = GPOINTER_TO_UINT (l->data);
4520 emit_method_code (acfg, acfg->cfgs [i]);
4523 sprintf (symbol, "methods_end");
4524 emit_section_change (acfg, ".text", 0);
4525 emit_global (acfg, symbol, FALSE);
4526 emit_alignment (acfg, 8);
4527 emit_label (acfg, symbol);
4529 sprintf (symbol, "method_offsets");
4530 emit_section_change (acfg, ".text", 1);
4531 emit_global (acfg, symbol, FALSE);
4532 emit_alignment (acfg, 8);
4533 emit_label (acfg, symbol);
4535 for (i = 0; i < acfg->nmethods; ++i) {
4536 if (acfg->cfgs [i]) {
4537 sprintf (symbol, ".Lm_%x", i);
4538 emit_symbol_diff (acfg, symbol, "methods", 0);
4540 emit_int32 (acfg, 0xffffffff);
4547 emit_info (MonoAotCompile *acfg)
4553 /* Emit method info */
4554 sprintf (symbol, "method_info");
4555 emit_section_change (acfg, ".text", 1);
4556 emit_global (acfg, symbol, FALSE);
4557 emit_alignment (acfg, 8);
4558 emit_label (acfg, symbol);
4560 /* To reduce size of generated assembly code */
4561 sprintf (symbol, "mi");
4562 emit_label (acfg, symbol);
4564 for (l = acfg->method_order; l != NULL; l = l->next) {
4565 i = GPOINTER_TO_UINT (l->data);
4568 emit_method_info (acfg, acfg->cfgs [i]);
4571 sprintf (symbol, "method_info_offsets");
4572 emit_section_change (acfg, ".text", 1);
4573 emit_global (acfg, symbol, FALSE);
4574 emit_alignment (acfg, 8);
4575 emit_label (acfg, symbol);
4577 for (i = 0; i < acfg->nmethods; ++i) {
4578 if (acfg->cfgs [i]) {
4579 sprintf (symbol, ".Lm_%x_p", i);
4580 emit_symbol_diff (acfg, symbol, "mi", 0);
4582 emit_int32 (acfg, 0);
4588 typedef struct HashEntry {
4589 guint32 key, value, index;
4590 struct HashEntry *next;
4594 * emit_extra_methods:
4596 * Emit methods which are not in the METHOD table, like wrappers.
4599 emit_extra_methods (MonoAotCompile *acfg)
4601 int i, table_size, buf_size;
4604 guint32 *info_offsets;
4607 HashEntry *entry, *new_entry;
4610 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4612 buf_size = acfg->extra_methods->len * 256 + 256;
4613 p = buf = g_malloc (buf_size);
4615 /* Encode method info */
4617 /* So offsets are > 0 */
4620 for (i = 0; i < acfg->extra_methods->len; ++i) {
4621 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4622 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4628 info_offsets [i] = p - buf;
4630 if (method->wrapper_type) {
4633 // FIXME: Optimize disk usage
4634 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
4635 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4636 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
4638 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
4639 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4640 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
4642 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
4643 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4644 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
4646 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
4647 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4648 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
4651 name = mono_method_full_name (cfg->orig_method, TRUE);
4654 encode_value (1, p, &p);
4655 strcpy ((char*)p, name);
4656 p += strlen (name ) + 1;
4659 encode_value (0, p, &p);
4660 encode_method_ref (acfg, method, p, &p);
4663 g_assert ((p - buf) < buf_size);
4666 g_assert ((p - buf) < buf_size);
4668 /* Emit method info */
4669 sprintf (symbol, "extra_method_info");
4670 emit_section_change (acfg, ".text", 1);
4671 emit_global (acfg, symbol, FALSE);
4672 emit_alignment (acfg, 8);
4673 emit_label (acfg, symbol);
4675 emit_bytes (acfg, buf, p - buf);
4680 * Construct a chained hash table for mapping indexes in extra_method_info to
4683 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4684 table = g_ptr_array_sized_new (table_size);
4685 for (i = 0; i < table_size; ++i)
4686 g_ptr_array_add (table, NULL);
4687 for (i = 0; i < acfg->extra_methods->len; ++i) {
4688 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4689 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4695 key = info_offsets [i];
4696 value = get_method_index (acfg, method);
4698 if (method->wrapper_type) {
4699 hash = g_str_hash (method->name) % table_size;
4702 hash = 0 % table_size;
4705 /* FIXME: Allocate from the mempool */
4706 new_entry = g_new0 (HashEntry, 1);
4707 new_entry->key = key;
4708 new_entry->value = value;
4710 entry = g_ptr_array_index (table, hash);
4711 if (entry == NULL) {
4712 new_entry->index = hash;
4713 g_ptr_array_index (table, hash) = new_entry;
4716 entry = entry->next;
4718 entry->next = new_entry;
4719 new_entry->index = table->len;
4720 g_ptr_array_add (table, new_entry);
4724 /* Emit the table */
4725 sprintf (symbol, "extra_method_table");
4726 emit_section_change (acfg, ".text", 0);
4727 emit_global (acfg, symbol, FALSE);
4728 emit_alignment (acfg, 8);
4729 emit_label (acfg, symbol);
4731 g_assert (table_size < 65000);
4732 emit_int32 (acfg, table_size);
4733 g_assert (table->len < 65000);
4734 for (i = 0; i < table->len; ++i) {
4735 HashEntry *entry = g_ptr_array_index (table, i);
4737 if (entry == NULL) {
4738 emit_int32 (acfg, 0);
4739 emit_int32 (acfg, 0);
4740 emit_int32 (acfg, 0);
4742 g_assert (entry->key > 0);
4743 emit_int32 (acfg, entry->key);
4744 emit_int32 (acfg, entry->value);
4746 emit_int32 (acfg, entry->next->index);
4748 emit_int32 (acfg, 0);
4753 * Emit a table reverse mapping method indexes to their index in extra_method_info.
4754 * This is used by mono_aot_find_jit_info ().
4756 sprintf (symbol, "extra_method_info_offsets");
4757 emit_section_change (acfg, ".text", 0);
4758 emit_global (acfg, symbol, FALSE);
4759 emit_alignment (acfg, 8);
4760 emit_label (acfg, symbol);
4762 emit_int32 (acfg, acfg->extra_methods->len);
4763 for (i = 0; i < acfg->extra_methods->len; ++i) {
4764 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4766 emit_int32 (acfg, get_method_index (acfg, method));
4767 emit_int32 (acfg, info_offsets [i]);
4772 emit_method_order (MonoAotCompile *acfg)
4778 sprintf (symbol, "method_order");
4779 emit_section_change (acfg, ".text", 1);
4780 emit_global (acfg, symbol, FALSE);
4781 emit_alignment (acfg, 8);
4782 emit_label (acfg, symbol);
4784 /* First emit an index table */
4787 for (l = acfg->method_order; l != NULL; l = l->next) {
4788 i = GPOINTER_TO_UINT (l->data);
4790 if (acfg->cfgs [i]) {
4791 if ((index % 1024) == 0) {
4792 emit_int32 (acfg, i);
4800 emit_int32 (acfg, 0xffffff);
4802 /* Then emit the whole method order */
4803 for (l = acfg->method_order; l != NULL; l = l->next) {
4804 i = GPOINTER_TO_UINT (l->data);
4806 if (acfg->cfgs [i]) {
4807 emit_int32 (acfg, i);
4812 sprintf (symbol, "method_order_end");
4813 emit_section_change (acfg, ".text", 1);
4814 emit_global (acfg, symbol, FALSE);
4815 emit_label (acfg, symbol);
4819 emit_exception_info (MonoAotCompile *acfg)
4824 sprintf (symbol, "ex_info");
4825 emit_section_change (acfg, ".text", 1);
4826 emit_global (acfg, symbol, FALSE);
4827 emit_alignment (acfg, 8);
4828 emit_label (acfg, symbol);
4830 /* To reduce size of generated assembly */
4831 sprintf (symbol, "ex");
4832 emit_label (acfg, symbol);
4834 for (i = 0; i < acfg->nmethods; ++i) {
4836 emit_exception_debug_info (acfg, acfg->cfgs [i]);
4839 sprintf (symbol, "ex_info_offsets");
4840 emit_section_change (acfg, ".text", 1);
4841 emit_global (acfg, symbol, FALSE);
4842 emit_alignment (acfg, 8);
4843 emit_label (acfg, symbol);
4845 for (i = 0; i < acfg->nmethods; ++i) {
4846 if (acfg->cfgs [i]) {
4847 sprintf (symbol, ".Le_%x_p", i);
4848 emit_symbol_diff (acfg, symbol, "ex", 0);
4850 emit_int32 (acfg, 0);
4857 emit_class_info (MonoAotCompile *acfg)
4862 sprintf (symbol, "class_info");
4863 emit_section_change (acfg, ".text", 1);
4864 emit_global (acfg, symbol, FALSE);
4865 emit_alignment (acfg, 8);
4866 emit_label (acfg, symbol);
4868 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4869 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4871 sprintf (symbol, "class_info_offsets");
4872 emit_section_change (acfg, ".text", 1);
4873 emit_global (acfg, symbol, FALSE);
4874 emit_alignment (acfg, 8);
4875 emit_label (acfg, symbol);
4877 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4878 sprintf (symbol, ".LK_I_%x", i);
4879 emit_symbol_diff (acfg, symbol, "class_info", 0);
4884 typedef struct ClassNameTableEntry {
4885 guint32 token, index;
4886 struct ClassNameTableEntry *next;
4887 } ClassNameTableEntry;
4890 emit_class_name_table (MonoAotCompile *acfg)
4893 guint32 token, hash;
4898 ClassNameTableEntry *entry, *new_entry;
4901 * Construct a chained hash table for mapping class names to typedef tokens.
4903 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4904 table = g_ptr_array_sized_new (table_size);
4905 for (i = 0; i < table_size; ++i)
4906 g_ptr_array_add (table, NULL);
4907 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4908 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4909 klass = mono_class_get (acfg->image, token);
4910 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4911 hash = g_str_hash (full_name) % table_size;
4914 /* FIXME: Allocate from the mempool */
4915 new_entry = g_new0 (ClassNameTableEntry, 1);
4916 new_entry->token = token;
4918 entry = g_ptr_array_index (table, hash);
4919 if (entry == NULL) {
4920 new_entry->index = hash;
4921 g_ptr_array_index (table, hash) = new_entry;
4924 entry = entry->next;
4926 entry->next = new_entry;
4927 new_entry->index = table->len;
4928 g_ptr_array_add (table, new_entry);
4932 /* Emit the table */
4933 sprintf (symbol, "class_name_table");
4934 emit_section_change (acfg, ".text", 0);
4935 emit_global (acfg, symbol, FALSE);
4936 emit_alignment (acfg, 8);
4937 emit_label (acfg, symbol);
4939 /* FIXME: Optimize memory usage */
4940 g_assert (table_size < 65000);
4941 emit_int16 (acfg, table_size);
4942 g_assert (table->len < 65000);
4943 for (i = 0; i < table->len; ++i) {
4944 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4946 if (entry == NULL) {
4947 emit_int16 (acfg, 0);
4948 emit_int16 (acfg, 0);
4950 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4952 emit_int16 (acfg, entry->next->index);
4954 emit_int16 (acfg, 0);
4960 emit_image_table (MonoAotCompile *acfg)
4966 * The image table is small but referenced in a lot of places.
4967 * So we emit it at once, and reference its elements by an index.
4970 sprintf (symbol, "mono_image_table");
4971 emit_section_change (acfg, ".text", 1);
4972 emit_global (acfg, symbol, FALSE);
4973 emit_alignment (acfg, 8);
4974 emit_label (acfg, symbol);
4976 emit_int32 (acfg, acfg->image_table->len);
4977 for (i = 0; i < acfg->image_table->len; i++) {
4978 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4979 MonoAssemblyName *aname = &image->assembly->aname;
4981 /* FIXME: Support multi-module assemblies */
4982 g_assert (image->assembly->image == image);
4984 emit_string (acfg, image->assembly_name);
4985 emit_string (acfg, image->guid);
4986 emit_string (acfg, aname->culture ? aname->culture : "");
4987 emit_string (acfg, (const char*)aname->public_key_token);
4989 emit_alignment (acfg, 8);
4990 emit_int32 (acfg, aname->flags);
4991 emit_int32 (acfg, aname->major);
4992 emit_int32 (acfg, aname->minor);
4993 emit_int32 (acfg, aname->build);
4994 emit_int32 (acfg, aname->revision);
4999 emit_got_info (MonoAotCompile *acfg)
5002 int i, first_plt_got_patch, buf_size;
5004 guint32 *got_info_offsets;
5006 /* Add the patches needed by the PLT to the GOT */
5007 acfg->plt_got_offset_base = acfg->got_offset;
5008 first_plt_got_patch = acfg->shared_patches->len;
5009 for (i = 1; i < acfg->plt_offset; ++i) {
5010 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
5012 g_ptr_array_add (acfg->shared_patches, patch_info);
5015 acfg->got_offset += acfg->plt_offset;
5019 * - optimize offsets table.
5020 * - reduce number of exported symbols.
5021 * - emit info for a klass only once.
5022 * - determine when a method uses a GOT slot which is guaranteed to be already
5024 * - clean up and document the code.
5025 * - use String.Empty in class libs.
5028 /* Encode info required to decode shared GOT entries */
5029 buf_size = acfg->shared_patches->len * 64;
5030 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5031 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
5032 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5033 for (i = 0; i < acfg->shared_patches->len; ++i) {
5034 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
5036 got_info_offsets [i] = p - buf;
5037 /* No need to encode the patch type for non-PLT patches */
5038 if (i >= first_plt_got_patch) {
5039 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5040 encode_value (ji->type, p, &p);
5042 encode_patch (acfg, ji, p, &p);
5045 g_assert (p - buf <= buf_size);
5047 acfg->stats.got_info_size = p - buf;
5049 /* Emit got_info table */
5050 sprintf (symbol, "got_info");
5051 emit_section_change (acfg, ".text", 1);
5052 emit_global (acfg, symbol, FALSE);
5053 emit_alignment (acfg, 8);
5054 emit_label (acfg, symbol);
5056 emit_bytes (acfg, buf, p - buf);
5058 /* Emit got_info_offsets table */
5059 sprintf (symbol, "got_info_offsets");
5060 emit_section_change (acfg, ".text", 1);
5061 emit_global (acfg, symbol, FALSE);
5062 emit_alignment (acfg, 8);
5063 emit_label (acfg, symbol);
5065 for (i = 0; i < acfg->shared_patches->len; ++i)
5066 emit_int32 (acfg, got_info_offsets [i]);
5068 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
5072 emit_got (MonoAotCompile *acfg)
5076 /* Don't make GOT global so accesses to it don't need relocations */
5077 sprintf (symbol, "got");
5078 emit_section_change (acfg, ".bss", 0);
5079 emit_alignment (acfg, 8);
5080 emit_label (acfg, symbol);
5081 if (acfg->got_offset > 0)
5082 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5086 emit_globals (MonoAotCompile *acfg)
5091 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5093 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5095 opts_str = g_strdup_printf ("%d", acfg->opts);
5096 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
5099 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
5101 if (acfg->aot_opts.bind_to_runtime_version) {
5102 build_info = mono_get_runtime_build_info ();
5103 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5104 g_free (build_info);
5106 emit_string_symbol (acfg, "mono_runtime_version", "");
5110 * Some platforms like the iphone have no working dlsym (). To work around this,
5111 * we create an ELF ctor function which will be invoked by dlopen, and which
5112 * will call a function in the AOT loader to register the symbols used by the
5114 * When static linking, we emit a global which will point to the symbol table.
5116 if (acfg->aot_opts.no_dlsym) {
5120 if (acfg->aot_opts.static_link)
5121 /* Emit a string holding the assembly name */
5122 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5124 /* Emit the names */
5125 for (i = 0; i < acfg->globals->len; ++i) {
5126 char *name = g_ptr_array_index (acfg->globals, i);
5128 sprintf (symbol, "name_%d", i);
5129 emit_section_change (acfg, ".text", 1);
5130 emit_label (acfg, symbol);
5131 emit_string (acfg, name);
5134 /* Emit the globals table */
5135 sprintf (symbol, "globals");
5136 emit_section_change (acfg, ".data", 0);
5137 /* This is not a global, since it is accessed by the init function */
5138 emit_alignment (acfg, 8);
5139 emit_label (acfg, symbol);
5141 for (i = 0; i < acfg->globals->len; ++i) {
5142 char *name = g_ptr_array_index (acfg->globals, i);
5144 sprintf (symbol, "name_%d", i);
5145 emit_pointer (acfg, symbol);
5147 sprintf (symbol, "%s", name);
5148 emit_pointer (acfg, symbol);
5150 /* Null terminate the table */
5151 emit_pointer (acfg, NULL);
5152 emit_pointer (acfg, NULL);
5154 if (acfg->aot_opts.static_link) {
5158 * Emit a global symbol which can be passed by an embedding app to
5159 * mono_aot_register_module ().
5161 #if defined(__MACH__)
5162 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5164 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5167 /* Get rid of characters which cannot occur in symbols */
5169 for (p = symbol; *p; ++p) {
5170 if (!(isalnum (*p) || *p == '_'))
5173 acfg->static_linking_symbol = g_strdup (symbol);
5174 emit_global_inner (acfg, symbol, FALSE);
5175 emit_alignment (acfg, 8);
5176 emit_label (acfg, symbol);
5177 emit_pointer (acfg, "globals");
5179 sprintf (symbol, "init_%s", acfg->image->assembly->aname.name);
5180 emit_section_change (acfg, ".text", 1);
5181 emit_alignment (acfg, 8);
5182 emit_label (acfg, symbol);
5183 #ifdef USE_BIN_WRITER
5184 g_assert_not_reached ();
5187 fprintf (acfg->fp, "leaq globals(%%rip), %%rdi\n");
5188 fprintf (acfg->fp, "call mono_aot_register_globals@PLT\n");
5189 fprintf (acfg->fp, "ret\n");
5190 fprintf (acfg->fp, ".section .ctors,\"aw\",@progbits\n");
5191 emit_alignment (acfg, 8);
5192 emit_pointer (acfg, symbol);
5193 #elif defined(__arm__) && defined(__MACH__)
5195 fprintf (acfg->fp, ".text\n");
5196 fprintf (acfg->fp, ".align 3\n");
5198 fprintf (acfg->fp, "ldr r0, .L5\n");
5199 fprintf (acfg->fp, ".LPIC0:\n");
5200 fprintf (acfg->fp, "add r0, pc, r0\n");
5201 fprintf (acfg->fp, "ldr r0, [r0]\n");
5202 fprintf (acfg->fp, "b _mono_aot_register_globals@PLT\n");
5203 fprintf (acfg->fp, ".align 2\n");
5205 fprintf (acfg->fp, ".L5:\n");
5206 fprintf (acfg->fp, ".long globals_ptr-(.LPIC0+8)\n");
5208 fprintf (acfg->fp, ".data\n");
5209 fprintf (acfg->fp, ".align 2\n");
5210 fprintf (acfg->fp, "globals_ptr:\n");
5211 fprintf (acfg->fp, ".long globals\n");
5213 fprintf (acfg->fp, ".mod_init_func\n");
5214 fprintf (acfg->fp, ".align 2\n");
5215 fprintf (acfg->fp, ".long %s@target1\n", symbol);
5217 #elif defined(__arm__)
5219 * Taken from gcc generated code for:
5221 * void foo () { bar (&i); }
5222 * gcc --shared -fPIC -O2
5224 fprintf (acfg->fp, "ldr r3, .L5\n");
5225 fprintf (acfg->fp, "ldr r0, .L5+4\n");
5226 fprintf (acfg->fp, ".LPIC0:\n");
5227 fprintf (acfg->fp, "add r3, pc, r3\n");
5228 fprintf (acfg->fp, "add r0, r3, r0\n");
5229 fprintf (acfg->fp, "b mono_aot_register_globals(PLT)\n");
5231 fprintf (acfg->fp, ".L5:\n");
5232 fprintf (acfg->fp, ".word _GLOBAL_OFFSET_TABLE_-(.LPIC0+8)\n");
5233 fprintf (acfg->fp, ".word globals(GOTOFF)\n");
5235 fprintf (acfg->fp, ".section .init_array,\"aw\",%%init_array\n");
5236 fprintf (acfg->fp, ".align 2\n");
5237 fprintf (acfg->fp, ".word %s(target1)\n", symbol);
5239 g_assert_not_reached ();
5247 * Emit a structure containing all the information not stored elsewhere.
5250 emit_file_info (MonoAotCompile *acfg)
5254 sprintf (symbol, "mono_aot_file_info");
5255 emit_section_change (acfg, ".data", 0);
5256 emit_alignment (acfg, 8);
5257 emit_label (acfg, symbol);
5258 emit_global (acfg, symbol, FALSE);
5260 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
5261 emit_int32 (acfg, acfg->plt_got_offset_base);
5262 emit_int32 (acfg, acfg->trampoline_got_offset_base);
5263 emit_int32 (acfg, acfg->num_aot_trampolines);
5264 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5265 emit_int32 (acfg, acfg->plt_offset);
5266 emit_pointer (acfg, "got");
5269 /*****************************************/
5270 /* Emitting DWARF debug information */
5271 /*****************************************/
5273 static G_GNUC_UNUSED void
5274 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
5277 guint8 b = value & 0x7f;
5279 if (value != 0) /* more bytes to come */
5281 emit_byte (acfg, b);
5285 static G_GNUC_UNUSED void
5286 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
5289 gboolean negative = (value < 0);
5294 byte = value & 0x7f;
5296 /* the following is unnecessary if the
5297 * implementation of >>= uses an arithmetic rather
5298 * than logical shift for a signed left operand
5302 value |= - ((gint64)1 <<(size - 7));
5303 /* sign bit of byte is second high order bit (0x40) */
5304 if ((value == 0 && !(byte & 0x40)) ||
5305 (value == -1 && (byte & 0x40)))
5309 emit_byte (acfg, byte);
5313 static G_GNUC_UNUSED void
5314 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
5319 guint8 b = value & 0x7f;
5321 if (value != 0) /* more bytes to come */
5329 static G_GNUC_UNUSED void
5330 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
5333 gboolean negative = (value < 0);
5339 byte = value & 0x7f;
5341 /* the following is unnecessary if the
5342 * implementation of >>= uses an arithmetic rather
5343 * than logical shift for a signed left operand
5347 value |= - (1 <<(size - 7));
5348 /* sign bit of byte is second high order bit (0x40) */
5349 if ((value == 0 && !(byte & 0x40)) ||
5350 (value == -1 && (byte & 0x40)))
5361 emit_dwarf_abbrev (MonoAotCompile *acfg, int code, int tag, gboolean has_child,
5362 int *attrs, int attrs_len)
5366 emit_uleb128 (acfg, code);
5367 emit_uleb128 (acfg, tag);
5368 emit_byte (acfg, has_child);
5370 for (i = 0; i < attrs_len; i++)
5371 emit_uleb128 (acfg, attrs [i]);
5372 emit_uleb128 (acfg, 0);
5373 emit_uleb128 (acfg, 0);
5377 emit_cie (MonoAotCompile *acfg)
5379 #if defined(__x86_64__) || defined(__arm__)
5380 emit_section_change (acfg, ".debug_frame", 0);
5382 emit_alignment (acfg, 8);
5385 emit_symbol_diff (acfg, ".Lcie0_end", ".", -4); /* length */
5386 emit_int32 (acfg, 0xffffffff); /* CIE id */
5387 emit_byte (acfg, 3); /* version */
5388 emit_string (acfg, ""); /* augmention */
5389 emit_sleb128 (acfg, 1); /* code alignment factor */
5391 emit_sleb128 (acfg, -8); /* data alignment factor */
5392 emit_uleb128 (acfg, AMD64_RIP);
5393 #elif defined(__arm__)
5394 emit_sleb128 (acfg, -4); /* data alignment factor */
5395 emit_uleb128 (acfg, mono_hw_reg_to_dwarf_reg (ARMREG_LR));
5397 g_assert_not_reached ();
5401 emit_byte (acfg, DW_CFA_def_cfa);
5402 emit_uleb128 (acfg, mono_hw_reg_to_dwarf_reg (AMD64_RSP));
5403 emit_uleb128 (acfg, 8); /* offset=8 */
5404 emit_byte (acfg, DW_CFA_offset | AMD64_RIP);
5405 emit_uleb128 (acfg, 1); /* offset=-8 */
5406 #elif defined(__arm__)
5408 g_assert_not_reached ();
5411 emit_alignment (acfg, sizeof (gpointer));
5412 emit_label (acfg, ".Lcie0_end");
5417 emit_pointer_value (MonoAotCompile *acfg, gpointer ptr)
5419 gssize val = (gssize)ptr;
5420 emit_bytes (acfg, (guint8*)&val, sizeof (gpointer));
5424 emit_fde (MonoAotCompile *acfg, int fde_index, char *start_symbol, char *end_symbol,
5425 guint8 *code, guint32 code_size, GSList *unwind_ops, gboolean use_cie)
5427 #if defined(__x86_64__) || defined(__arm__)
5431 guint32 uw_info_len;
5436 * The debugger can unwind without unwind info, but gets confused by empty
5442 emit_section_change (acfg, ".debug_frame", 0);
5444 sprintf (symbol, ".Lfde%d_end", fde_index);
5445 emit_symbol_diff (acfg, symbol, ".", -4); /* length */
5446 emit_int32 (acfg, 0); /* CIE_pointer */
5448 emit_pointer (acfg, start_symbol); /* initial_location */
5449 emit_symbol_diff (acfg, end_symbol, start_symbol, 0); /* address_range */
5451 emit_pointer_value (acfg, code);
5452 emit_int32 (acfg, code_size);
5454 #if SIZEOF_VOID_P == 8
5455 /* Upper 32 bits of code size */
5456 emit_int32 (acfg, 0);
5462 /* Skip the first two ops which are in the CIE */
5466 /* Convert the list of MonoUnwindOps to the format used by DWARF */
5467 uw_info = mono_unwind_ops_encode (l, &uw_info_len);
5468 emit_bytes (acfg, uw_info, uw_info_len);
5471 emit_alignment (acfg, sizeof (gpointer));
5472 sprintf (symbol, ".Lfde%d_end", fde_index);
5473 emit_label (acfg, symbol);
5478 #define AB_COMPILE_UNIT 1
5479 #define AB_SUBPROGRAM 2
5481 #define AB_BASE_TYPE 4
5482 #define AB_STRUCT_TYPE 5
5483 #define AB_DATA_MEMBER 6
5484 #define AB_TYPEDEF 7
5485 #define AB_ENUM_TYPE 8
5486 #define AB_ENUMERATOR 9
5487 #define AB_NAMESPACE 10
5488 #define AB_VARIABLE 11
5490 static int compile_unit_attr [] = {
5491 DW_AT_producer ,DW_FORM_string,
5492 DW_AT_name ,DW_FORM_string,
5493 DW_AT_comp_dir ,DW_FORM_string,
5494 DW_AT_language ,DW_FORM_data1,
5495 DW_AT_low_pc ,DW_FORM_addr,
5496 DW_AT_high_pc ,DW_FORM_addr,
5497 DW_AT_stmt_list ,DW_FORM_data4
5500 static int subprogram_attr [] = {
5501 DW_AT_name , DW_FORM_string,
5502 DW_AT_low_pc , DW_FORM_addr,
5503 DW_AT_high_pc , DW_FORM_addr,
5504 DW_AT_frame_base , DW_FORM_block1
5507 static int param_attr [] = {
5508 DW_AT_name, DW_FORM_string,
5509 DW_AT_type, DW_FORM_ref4,
5510 DW_AT_location, DW_FORM_block1
5513 static int base_type_attr [] = {
5514 DW_AT_byte_size, DW_FORM_data1,
5515 DW_AT_encoding, DW_FORM_data1,
5516 DW_AT_name, DW_FORM_string
5519 static int struct_type_attr [] = {
5520 DW_AT_name, DW_FORM_string,
5521 DW_AT_byte_size, DW_FORM_udata,
5524 static int data_member_attr [] = {
5525 DW_AT_name, DW_FORM_string,
5526 DW_AT_type, DW_FORM_ref4,
5527 DW_AT_data_member_location, DW_FORM_block1
5530 static int typedef_attr [] = {
5531 DW_AT_name, DW_FORM_string,
5532 DW_AT_type, DW_FORM_ref4
5535 static int enum_type_attr [] = {
5536 DW_AT_name, DW_FORM_string,
5537 DW_AT_byte_size, DW_FORM_udata,
5538 DW_AT_type, DW_FORM_ref4,
5541 static int enumerator_attr [] = {
5542 DW_AT_name, DW_FORM_string,
5543 DW_AT_const_value, DW_FORM_sdata,
5546 static int namespace_attr [] = {
5547 DW_AT_name, DW_FORM_string,
5550 static int variable_attr [] = {
5551 DW_AT_name, DW_FORM_string,
5552 DW_AT_type, DW_FORM_ref4,
5553 DW_AT_location, DW_FORM_block1
5556 typedef struct DwarfBasicType {
5557 const char *die_name, *name;
5563 static DwarfBasicType basic_types [] = {
5564 { ".LDIE_I1", "sbyte", MONO_TYPE_I1, 1, DW_ATE_signed },
5565 { ".LDIE_U1", "byte", MONO_TYPE_U1, 1, DW_ATE_unsigned },
5566 { ".LDIE_I2", "short", MONO_TYPE_I2, 2, DW_ATE_signed },
5567 { ".LDIE_U2", "ushort", MONO_TYPE_U2, 2, DW_ATE_unsigned },
5568 { ".LDIE_I4", "int", MONO_TYPE_I4, 4, DW_ATE_signed },
5569 { ".LDIE_U4", "uint", MONO_TYPE_U4, 4, DW_ATE_unsigned },
5570 { ".LDIE_I8", "long", MONO_TYPE_I8, 8, DW_ATE_signed },
5571 { ".LDIE_U8", "ulong", MONO_TYPE_U8, 8, DW_ATE_unsigned },
5572 { ".LDIE_R4", "float", MONO_TYPE_R4, 4, DW_ATE_float },
5573 { ".LDIE_R8", "double", MONO_TYPE_R8, 8, DW_ATE_float },
5574 { ".LDIE_BOOLEAN", "boolean", MONO_TYPE_BOOLEAN, 1, DW_ATE_boolean },
5575 { ".LDIE_STRING", "string", MONO_TYPE_STRING, sizeof (gpointer), DW_ATE_address },
5576 { ".LDIE_OBJECT", "object", MONO_TYPE_OBJECT, sizeof (gpointer), DW_ATE_address },
5577 { ".LDIE_SZARRAY", "object", MONO_TYPE_SZARRAY, sizeof (gpointer), DW_ATE_address },
5580 /* Constants for encoding line number special opcodes*/
5581 #define OPCODE_BASE 13
5582 #define LINE_BASE -5
5583 #define LINE_RANGE 14
5586 emit_line_number_file_name (MonoAotCompile *acfg, const char *name, int dir_index,
5587 gint64 last_mod_time, gint64 file_size)
5589 int index = acfg->line_number_file_index ++;
5591 emit_string (acfg, name);
5592 emit_byte (acfg, 0);
5593 emit_byte (acfg, 0);
5594 emit_byte (acfg, 0);
5600 emit_base_dwarf_info (MonoAotCompile *acfg)
5602 char *s, *build_info;
5605 emit_section_change (acfg, ".debug_abbrev", 0);
5606 emit_dwarf_abbrev (acfg, AB_COMPILE_UNIT, DW_TAG_compile_unit, TRUE,
5607 compile_unit_attr, G_N_ELEMENTS (compile_unit_attr));
5608 emit_dwarf_abbrev (acfg, AB_SUBPROGRAM, DW_TAG_subprogram, TRUE,
5609 subprogram_attr, G_N_ELEMENTS (subprogram_attr));
5610 emit_dwarf_abbrev (acfg, AB_PARAM, DW_TAG_formal_parameter, FALSE,
5611 param_attr, G_N_ELEMENTS (param_attr));
5612 emit_dwarf_abbrev (acfg, AB_BASE_TYPE, DW_TAG_base_type, FALSE,
5613 base_type_attr, G_N_ELEMENTS (base_type_attr));
5614 emit_dwarf_abbrev (acfg, AB_STRUCT_TYPE, DW_TAG_class_type, TRUE,
5615 struct_type_attr, G_N_ELEMENTS (struct_type_attr));
5616 emit_dwarf_abbrev (acfg, AB_DATA_MEMBER, DW_TAG_member, FALSE,
5617 data_member_attr, G_N_ELEMENTS (data_member_attr));
5618 emit_dwarf_abbrev (acfg, AB_TYPEDEF, DW_TAG_typedef, FALSE,
5619 typedef_attr, G_N_ELEMENTS (typedef_attr));
5620 emit_dwarf_abbrev (acfg, AB_ENUM_TYPE, DW_TAG_enumeration_type, TRUE,
5621 enum_type_attr, G_N_ELEMENTS (enum_type_attr));
5622 emit_dwarf_abbrev (acfg, AB_ENUMERATOR, DW_TAG_enumerator, FALSE,
5623 enumerator_attr, G_N_ELEMENTS (enumerator_attr));
5624 emit_dwarf_abbrev (acfg, AB_NAMESPACE, DW_TAG_namespace, TRUE,
5625 namespace_attr, G_N_ELEMENTS (namespace_attr));
5626 emit_dwarf_abbrev (acfg, AB_VARIABLE, DW_TAG_variable, FALSE,
5627 variable_attr, G_N_ELEMENTS (variable_attr));
5628 emit_byte (acfg, 0);
5630 emit_section_change (acfg, ".debug_info", 0);
5631 emit_label (acfg, ".Ldebug_info_start");
5632 emit_symbol_diff (acfg, ".Ldebug_info_end", ".", -4); /* length */
5633 emit_int16 (acfg, 0x3); /* DWARF version 3 */
5634 emit_int32 (acfg, 0); /* .debug_abbrev offset */
5635 emit_byte (acfg, sizeof (gpointer)); /* address size */
5637 /* Emit this into a separate section so it gets placed at the end */
5638 emit_section_change (acfg, ".debug_info", 1);
5639 emit_int32 (acfg, 0); /* close everything */
5640 emit_label (acfg, ".Ldebug_info_end");
5641 emit_section_change (acfg, ".debug_info", 0);
5643 /* Compilation unit */
5644 emit_uleb128 (acfg, AB_COMPILE_UNIT);
5645 build_info = mono_get_runtime_build_info ();
5646 s = g_strdup_printf ("Mono AOT Compiler %s", build_info);
5647 emit_string (acfg, s);
5648 g_free (build_info);
5650 emit_string (acfg, "JITted code");
5651 emit_string (acfg, "");
5652 emit_byte (acfg, DW_LANG_C);
5653 emit_pointer_value (acfg, 0);
5654 emit_pointer_value (acfg, 0);
5655 /* offset into .debug_line section */
5656 emit_symbol_diff (acfg, ".Ldebug_line_start", ".Ldebug_line_section_start", 0);
5659 for (i = 0; i < G_N_ELEMENTS (basic_types); ++i) {
5660 emit_label (acfg, basic_types [i].die_name);
5661 emit_uleb128 (acfg, AB_BASE_TYPE);
5662 emit_byte (acfg, basic_types [i].size);
5663 emit_byte (acfg, basic_types [i].encoding);
5664 emit_string (acfg, basic_types [i].name);
5667 /* Line number info header */
5669 * GAS seems to emit its own data to the end of the first subsection, so we use
5670 * subsections 1, 2 etc:
5671 * 1 - contains the header
5672 * 2 - contains the file names
5673 * 3 - contains the end of the header + the data
5674 * 4 - the end symbol
5676 emit_section_change (acfg, ".debug_line", 0);
5677 emit_label (acfg, ".Ldebug_line_section_start");
5678 emit_section_change (acfg, ".debug_line", 1);
5679 emit_label (acfg, ".Ldebug_line_start");
5680 emit_symbol_diff (acfg, ".Ldebug_line_end", ".", -4); /* length */
5681 emit_int16 (acfg, 0x2); /* version */
5682 emit_symbol_diff (acfg, ".Ldebug_line_header_end", ".", -4); /* header_length */
5683 emit_byte (acfg, 1); /* minimum_instruction_length */
5684 emit_byte (acfg, 1); /* default_is_stmt */
5685 emit_byte (acfg, LINE_BASE); /* line_base */
5686 emit_byte (acfg, LINE_RANGE); /* line_range */
5687 emit_byte (acfg, OPCODE_BASE); /* opcode_base */
5688 emit_byte (acfg, 0); /* standard_opcode_lengths */
5689 emit_byte (acfg, 1);
5690 emit_byte (acfg, 1);
5691 emit_byte (acfg, 1);
5692 emit_byte (acfg, 1);
5693 emit_byte (acfg, 0);
5694 emit_byte (acfg, 0);
5695 emit_byte (acfg, 0);
5696 emit_byte (acfg, 1);
5697 emit_byte (acfg, 0);
5698 emit_byte (acfg, 0);
5699 emit_byte (acfg, 1);
5700 emit_byte (acfg, 0); /* include_directories */
5702 /* Emit this into a separate subsection so it can be appended to */
5703 emit_section_change (acfg, ".debug_line", 2);
5704 emit_line_number_file_name (acfg, "<IL>", 0, 0, 0);
5706 /* End of file_table */
5707 emit_section_change (acfg, ".debug_line", 3);
5708 emit_byte (acfg, 0);
5710 emit_label (acfg, ".Ldebug_line_header_end");
5712 /* Emit this into a separate subsection so it gets placed at the end */
5713 emit_section_change (acfg, ".debug_line", 4);
5715 emit_byte (acfg, 0);
5716 emit_byte (acfg, 1);
5717 emit_byte (acfg, DW_LNE_end_sequence);
5719 emit_label (acfg, ".Ldebug_line_end");
5724 /* Returns the local symbol pointing to the emitted debug info */
5726 emit_class_dwarf_info (MonoAotCompile *acfg, MonoClass *klass)
5731 MonoClassField *field;
5734 gboolean emit_namespace = FALSE;
5736 // FIXME: Appdomains
5737 if (!acfg->class_to_die)
5738 acfg->class_to_die = g_hash_table_new (NULL, NULL);
5740 die = g_hash_table_lookup (acfg->class_to_die, klass);
5744 if (!((klass->byval_arg.type == MONO_TYPE_CLASS) || klass->enumtype))
5748 * FIXME: gdb can't handle namespaces in languages it doesn't know about.
5751 if (klass->name_space && klass->name_space [0] != '\0')
5752 emit_namespace = TRUE;
5754 if (emit_namespace) {
5755 emit_uleb128 (acfg, AB_NAMESPACE);
5756 emit_string (acfg, klass->name_space);
5759 full_name = g_strdup_printf ("%s%s%s", klass->name_space, klass->name_space ? "." : "", klass->name);
5761 die = g_strdup_printf (".LTDIE_%d", acfg->tdie_index);
5762 emit_label (acfg, die);
5764 if (klass->enumtype) {
5765 int size = mono_class_value_size (mono_class_from_mono_type (klass->enum_basetype), NULL);
5767 emit_uleb128 (acfg, AB_ENUM_TYPE);
5768 emit_string (acfg, full_name);
5769 emit_uleb128 (acfg, size);
5770 for (k = 0; k < G_N_ELEMENTS (basic_types); ++k)
5771 if (basic_types [k].type == klass->enum_basetype->type)
5773 g_assert (k < G_N_ELEMENTS (basic_types));
5774 emit_symbol_diff (acfg, basic_types [k].die_name, ".Ldebug_info_start", 0);
5776 /* Emit enum values */
5778 while ((field = mono_class_get_fields (klass, &iter))) {
5781 MonoTypeEnum def_type;
5783 if (strcmp ("value__", mono_field_get_name (field)) == 0)
5785 if (mono_field_is_deleted (field))
5788 emit_uleb128 (acfg, AB_ENUMERATOR);
5789 emit_string (acfg, mono_field_get_name (field));
5791 p = mono_class_get_field_default_value (field, &def_type);
5792 len = mono_metadata_decode_blob_size (p, &p);
5793 switch (klass->enum_basetype->type) {
5796 emit_sleb128 (acfg, *p);
5798 case MONO_TYPE_CHAR:
5801 emit_sleb128 (acfg, read16 (p));
5805 emit_sleb128 (acfg, read32 (p));
5809 emit_sleb128 (acfg, read64 (p));
5812 g_assert_not_reached ();
5816 emit_uleb128 (acfg, AB_STRUCT_TYPE);
5817 emit_string (acfg, full_name);
5818 emit_uleb128 (acfg, klass->instance_size);
5822 while ((field = mono_class_get_fields (klass, &iter))) {
5826 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
5829 for (k = 0; k < G_N_ELEMENTS (basic_types); ++k)
5830 if (basic_types [k].type == field->type->type)
5832 if (k < G_N_ELEMENTS (basic_types) && field->type->type != MONO_TYPE_SZARRAY && field->type->type != MONO_TYPE_CLASS) {
5833 fdie = basic_types [k].die_name;
5835 emit_uleb128 (acfg, AB_DATA_MEMBER);
5836 emit_string (acfg, field->name);
5837 emit_symbol_diff (acfg, fdie, ".Ldebug_info_start", 0);
5840 *p ++= DW_OP_plus_uconst;
5841 encode_uleb128 (field->offset, p, &p);
5843 emit_byte (acfg, p - buf);
5844 emit_bytes (acfg, buf, p - buf);
5850 emit_uleb128 (acfg, 0x0);
5852 /* Add a typedef, so we can reference the type without a 'struct' in gdb */
5853 emit_uleb128 (acfg, AB_TYPEDEF);
5854 emit_string (acfg, full_name);
5855 emit_symbol_diff (acfg, die, ".Ldebug_info_start", 0);
5858 acfg->tdie_index ++;
5861 if (emit_namespace) {
5863 emit_uleb128 (acfg, 0x0);
5866 g_hash_table_insert (acfg->class_to_die, klass, die);
5871 emit_var_type (MonoAotCompile *acfg, MonoType *t)
5873 MonoClass *klass = mono_class_from_mono_type (t);
5877 for (j = 0; j < G_N_ELEMENTS (basic_types); ++j)
5878 if (basic_types [j].type == t->type)
5880 if (j < G_N_ELEMENTS (basic_types))
5881 tdie = basic_types [j].die_name;
5884 case MONO_TYPE_CLASS:
5885 case MONO_TYPE_ARRAY:
5886 tdie = ".LDIE_OBJECT";
5888 case MONO_TYPE_VALUETYPE:
5889 if (klass->enumtype)
5890 tdie = emit_class_dwarf_info (acfg, klass);
5902 emit_symbol_diff (acfg, tdie, ".Ldebug_info_start", 0);
5906 emit_var_location (MonoAotCompile *acfg, MonoInst *ins)
5909 /* FIXME: This needs a location list, since the args can go from reg->stack */
5910 if (!ins || ins->flags & MONO_INST_IS_DEAD) {
5911 /* gdb treats this as optimized out */
5912 emit_byte (acfg, 0);
5913 } else if (ins->opcode == OP_REGVAR) {
5914 emit_byte (acfg, 1);
5915 emit_byte (acfg, DW_OP_reg0 + mono_hw_reg_to_dwarf_reg (ins->dreg));
5916 } else if (ins->opcode == OP_REGOFFSET) {
5921 *p ++= DW_OP_breg0 + mono_hw_reg_to_dwarf_reg (ins->inst_basereg);
5922 encode_sleb128 (ins->inst_offset, p, &p);
5923 emit_byte (acfg, p - buf);
5924 emit_bytes (acfg, buf, p - buf);
5927 emit_byte (acfg, 1);
5928 emit_byte (acfg, DW_OP_reg0);
5933 emit_method_dwarf_info (MonoAotCompile *acfg, MonoMethod *method, char *start_symbol, char *end_symbol, guint8 *code, guint32 code_size, MonoInst **args, MonoInst **locals, GSList *unwind_info, MonoDebugMethodJitInfo *debug_info)
5936 MonoMethodSignature *sig;
5937 MonoMethodHeader *header;
5938 char **names, **tdies, **local_tdies;
5943 emit_section_change (acfg, ".debug_info", 0);
5945 sig = mono_method_signature (method);
5946 header = mono_method_get_header (method);
5948 /* Parameter types */
5949 tdies = g_new0 (char *, sig->param_count + sig->hasthis);
5950 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5953 if (i == 0 && sig->hasthis) {
5954 t = &method->klass->this_arg;
5956 t = sig->params [i - sig->hasthis];
5959 emit_class_dwarf_info (acfg, mono_class_from_mono_type (t));
5963 local_tdies = g_new0 (char *, header->num_locals);
5964 for (i = 0; i < header->num_locals; ++i) {
5965 emit_class_dwarf_info (acfg, mono_class_from_mono_type (header->locals [i]));
5969 names = g_new0 (char *, sig->param_count);
5970 mono_method_get_param_names (method, (const char **) names);
5972 emit_uleb128 (acfg, AB_SUBPROGRAM);
5973 name = mono_method_full_name (method, FALSE);
5974 emit_string (acfg, name);
5977 emit_pointer_unaligned (acfg, start_symbol);
5978 emit_pointer_unaligned (acfg, end_symbol);
5980 emit_pointer_value (acfg, code);
5981 emit_pointer_value (acfg, code + code_size);
5984 emit_byte (acfg, 2);
5985 emit_byte (acfg, DW_OP_breg6);
5986 emit_byte (acfg, 16);
5989 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5990 MonoInst *arg = args ? args [i] : NULL;
5993 char pname_buf [128];
5995 if (i == 0 && sig->hasthis) {
5996 t = &mono_defaults.object_class->byval_arg;
5999 t = sig->params [i - sig->hasthis];
6000 pname = names [i - sig->hasthis];
6003 emit_uleb128 (acfg, AB_PARAM);
6005 if (pname[0] == '\0') {
6006 sprintf (pname_buf, "param%d", i - sig->hasthis);
6009 emit_string (acfg, pname);
6011 if (!arg || arg->flags & MONO_INST_IS_DEAD)
6012 emit_var_type (acfg, &mono_defaults.int32_class->byval_arg);
6014 emit_var_type (acfg, t);
6015 emit_var_location (acfg, arg);
6020 num_locals = mono_debug_lookup_locals (method, &local_names, &local_indexes);
6022 for (i = 0; i < header->num_locals; ++i) {
6023 MonoInst *ins = locals [i];
6024 char name_buf [128];
6027 emit_uleb128 (acfg, AB_VARIABLE);
6029 for (j = 0; j < num_locals; ++j)
6030 if (local_indexes [j] == i)
6032 if (j < num_locals) {
6033 emit_string (acfg, local_names [j]);
6035 sprintf (name_buf, "V_%d", i);
6036 emit_string (acfg, name_buf);
6039 if (!ins || ins->flags & MONO_INST_IS_DEAD)
6040 emit_var_type (acfg, &mono_defaults.int32_class->byval_arg);
6042 emit_var_type (acfg, header->locals [i]);
6043 emit_var_location (acfg, ins);
6046 g_free (local_names);
6047 g_free (local_indexes);
6049 /* Subprogram end */
6050 emit_uleb128 (acfg, 0x0);
6054 /* Emit unwind info */
6055 emit_fde (acfg, acfg->fde_index, start_symbol, end_symbol, code, code_size, unwind_info, TRUE);
6058 /* Emit line number info */
6059 if (code && debug_info) {
6060 guint32 prev_line = 0;
6061 guint32 prev_native_offset = 0;
6063 gboolean first = TRUE;
6064 MonoDebugSourceLocation *loc;
6065 char *prev_file_name = NULL;
6067 // FIXME: Generate optimized bytecode
6071 for (i = 0; i < code_size; ++i) {
6072 loc = mono_debug_lookup_source_location (method, i, mono_domain_get ());
6076 emit_section_change (acfg, ".debug_line", 3);
6078 emit_byte (acfg, 0);
6079 emit_byte (acfg, sizeof (gpointer) + 1);
6080 emit_byte (acfg, DW_LNE_set_address);
6081 emit_pointer_value (acfg, code);
6086 if (!prev_file_name || strcmp (loc->source_file, prev_file_name) != 0) {
6087 /* Add an entry to the file table */
6088 /* FIXME: Avoid duplicates */
6089 emit_section_change (acfg, ".debug_line", 2);
6090 file_index = emit_line_number_file_name (acfg, loc->source_file, 0, 0, 0);
6091 emit_section_change (acfg, ".debug_line", 3);
6092 g_free (prev_file_name);
6093 prev_file_name = g_strdup (loc->source_file);
6095 emit_byte (acfg, DW_LNS_set_file);
6096 emit_uleb128 (acfg, file_index);
6097 emit_byte (acfg, DW_LNS_copy);
6100 if (loc->row != prev_line) {
6101 int line_diff = (gint32)loc->row - (gint32)prev_line;
6102 int addr_diff = i - prev_native_offset;
6105 //printf ("X: %p(+0x%x) %d %s:%d(+%d)\n", code + i, addr_diff, loc->il_offset, loc->source_file, loc->row, line_diff);
6108 /* Use a special opcode if possible */
6109 if (line_diff - LINE_BASE < LINE_RANGE) {
6110 opcode = (line_diff - LINE_BASE) + (LINE_RANGE * addr_diff) + OPCODE_BASE;
6116 emit_byte (acfg, opcode);
6118 emit_byte (acfg, DW_LNS_advance_line);
6119 emit_sleb128 (acfg, (gint32)loc->row - (gint32)prev_line);
6120 emit_byte (acfg, DW_LNS_advance_pc);
6121 emit_sleb128 (acfg, i - prev_native_offset);
6122 emit_byte (acfg, DW_LNS_copy);
6125 prev_line = loc->row;
6126 prev_native_offset = i;
6133 g_free (prev_file_name);
6136 emit_byte (acfg, DW_LNS_advance_pc);
6137 emit_sleb128 (acfg, code_size - prev_native_offset);
6138 emit_byte (acfg, DW_LNS_copy);
6140 emit_byte (acfg, 0);
6141 emit_byte (acfg, 1);
6142 emit_byte (acfg, DW_LNE_end_sequence);
6150 emit_trampoline_dwarf_info (MonoAotCompile *acfg, const char *tramp_name, char *start_symbol, char *end_symbol, guint8 *code, guint32 code_size, GSList *unwind_info)
6152 emit_section_change (acfg, ".debug_info", 0);
6155 emit_uleb128 (acfg, AB_SUBPROGRAM);
6156 emit_string (acfg, tramp_name);
6157 emit_pointer_value (acfg, code);
6158 emit_pointer_value (acfg, code + code_size);
6160 emit_byte (acfg, 2);
6161 emit_byte (acfg, DW_OP_breg6);
6162 emit_byte (acfg, 16);
6164 /* Subprogram end */
6165 emit_uleb128 (acfg, 0x0);
6167 /* Emit unwind info */
6168 emit_fde (acfg, acfg->fde_index, NULL, NULL, code, code_size, unwind_info, FALSE);
6173 emit_dwarf_info (MonoAotCompile *acfg)
6175 #if defined(USE_ELF_WRITER) && defined(__x86_64__)
6177 char symbol [128], symbol2 [128];
6179 emit_base_dwarf_info (acfg);
6181 /* DIEs for methods */
6182 for (i = 0; i < acfg->nmethods; ++i) {
6183 MonoCompile *cfg = acfg->cfgs [i];
6188 sprintf (symbol, ".Lm_%x", i);
6189 sprintf (symbol2, ".Lme_%x", i);
6191 emit_method_dwarf_info (acfg, cfg->method, symbol, symbol2, NULL, 0, cfg->args, cfg->locals, cfg->unwind_ops, NULL);
6193 #endif /* ELF_WRITER */
6197 acfg_free (MonoAotCompile *acfg)
6201 for (i = 0; i < acfg->nmethods; ++i)
6203 g_free (acfg->cfgs [i]);
6204 g_free (acfg->cfgs);
6205 g_free (acfg->static_linking_symbol);
6206 g_ptr_array_free (acfg->methods, TRUE);
6207 g_ptr_array_free (acfg->shared_patches, TRUE);
6208 g_ptr_array_free (acfg->image_table, TRUE);
6209 g_ptr_array_free (acfg->globals, TRUE);
6210 g_hash_table_destroy (acfg->method_indexes);
6211 g_hash_table_destroy (acfg->plt_offset_to_patch);
6212 g_hash_table_destroy (acfg->patch_to_plt_offset);
6213 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
6214 g_hash_table_destroy (acfg->method_to_cfg);
6215 g_hash_table_destroy (acfg->token_info_hash);
6216 g_hash_table_destroy (acfg->image_hash);
6217 mono_mempool_destroy (acfg->mempool);
6222 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6224 MonoImage *image = ass->image;
6226 int i, res, methods_len;
6227 MonoAotCompile *acfg;
6231 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6233 acfg = g_new0 (MonoAotCompile, 1);
6234 acfg->methods = g_ptr_array_new ();
6235 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6236 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
6237 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6238 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6239 acfg->shared_patches = g_ptr_array_new ();
6240 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6241 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6242 acfg->image_hash = g_hash_table_new (NULL, NULL);
6243 acfg->image_table = g_ptr_array_new ();
6244 acfg->globals = g_ptr_array_new ();
6245 acfg->image = image;
6247 acfg->mempool = mono_mempool_new ();
6248 acfg->extra_methods = g_ptr_array_new ();
6249 InitializeCriticalSection (&acfg->mutex);
6251 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6252 acfg->aot_opts.write_symbols = TRUE;
6254 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6256 #ifdef USE_BIN_WRITER
6257 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer)
6258 acfg->use_bin_writer = TRUE;
6261 load_profile_files (acfg);
6265 acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 10240 : 0;
6267 acfg->method_index = 1;
6269 /* Collect methods */
6270 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
6272 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
6274 method = mono_get_method (acfg->image, token, NULL);
6276 /* Load all methods eagerly to skip the slower lazy loading code */
6277 mono_class_setup_methods (method->klass);
6279 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6280 /* Compile the wrapper instead */
6281 /* We do this here instead of add_wrappers () because it is easy to do it here */
6282 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
6286 /* Since we add the normal methods first, their index will be equal to their zero based token index */
6287 add_method_with_index (acfg, method, i);
6288 acfg->method_index ++;
6291 add_generic_instances (acfg);
6293 if (acfg->aot_opts.full_aot)
6294 add_wrappers (acfg);
6296 acfg->cfgs_size = acfg->methods->len + 32;
6297 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6299 /* PLT offset 0 is reserved for the PLT trampoline */
6300 acfg->plt_offset = 1;
6302 /* Compile methods */
6305 if (acfg->aot_opts.nthreads > 0) {
6310 gpointer *user_data;
6311 MonoMethod **methods;
6313 methods_len = acfg->methods->len;
6315 len = acfg->methods->len / acfg->aot_opts.nthreads;
6318 * Partition the list of methods into fragments, and hand it to threads to
6321 threads = g_ptr_array_new ();
6322 /* Make a copy since acfg->methods is modified by compile_method () */
6323 methods = g_new0 (MonoMethod*, methods_len);
6324 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6325 for (i = 0; i < methods_len; ++i)
6326 methods [i] = g_ptr_array_index (acfg->methods, i);
6328 while (i < methods_len) {
6329 frag = g_ptr_array_new ();
6330 for (j = 0; j < len; ++j) {
6331 if (i < methods_len) {
6332 g_ptr_array_add (frag, methods [i]);
6337 user_data = g_new0 (gpointer, 3);
6338 user_data [0] = mono_domain_get ();
6339 user_data [1] = acfg;
6340 user_data [2] = frag;
6342 handle = CreateThread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6343 g_ptr_array_add (threads, handle);
6347 for (i = 0; i < threads->len; ++i) {
6348 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6354 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6355 for (i = methods_len; i < acfg->methods->len; ++i) {
6356 /* This can new methods to acfg->methods */
6357 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6362 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6366 alloc_got_slots (acfg);
6372 emit_extra_methods (acfg);
6374 emit_method_order (acfg);
6376 emit_trampolines (acfg);
6378 emit_class_name_table (acfg);
6380 emit_got_info (acfg);
6382 emit_exception_info (acfg);
6384 emit_class_info (acfg);
6388 emit_image_table (acfg);
6392 emit_file_info (acfg);
6394 emit_globals (acfg);
6396 emit_dwarf_info (acfg);
6398 sprintf (symbol, "mem_end");
6399 emit_section_change (acfg, ".text", 1);
6400 emit_global (acfg, symbol, FALSE);
6401 emit_alignment (acfg, 8);
6402 emit_label (acfg, symbol);
6406 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6408 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)));
6411 res = emit_writeout (acfg);
6417 acfg->stats.link_time = TV_ELAPSED (atv, btv);
6419 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);
6420 if (acfg->stats.genericcount)
6421 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6422 if (acfg->stats.abscount)
6423 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6424 if (acfg->stats.lmfcount)
6425 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6426 if (acfg->stats.ocount)
6427 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6428 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);
6429 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6430 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);
6432 printf ("GOT slot distribution:\n");
6433 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6434 if (acfg->stats.got_slot_types [i])
6435 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6443 * Support for emitting debug info for JITted code.
6445 * This works as follows:
6446 * - the runtime writes out an xdb.s file containing DWARF debug info.
6447 * - the user calls a gdb macro
6448 * - the macro compiles and loads this shared library using add-symbol-file.
6450 * This is based on the xdebug functionality in the Kaffe Java VM.
6452 * We emit assembly code instead of using the ELF writer, so we can emit debug info
6453 * incrementally as each method is JITted, and the debugger doesn't have to call
6454 * into the runtime to emit the shared library, which would cause all kinds of
6455 * complications, like threading issues, and the fact that the ELF writer's
6456 * emit_writeout () function cannot be called more than once.
6459 /* The recommended gdb macro is: */
6462 shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
6463 add-symbol-file xdb.so 0
6467 static MonoAotCompile *xdebug_acfg;
6470 mono_xdebug_init (void)
6472 MonoAotCompile *acfg;
6474 acfg = g_new0 (MonoAotCompile, 1);
6475 acfg->mempool = mono_mempool_new ();
6476 InitializeCriticalSection (&acfg->mutex);
6477 acfg->aot_opts.asm_only = TRUE;
6478 acfg->aot_opts.outfile = g_strdup ("xdb.s");
6486 /* Emit something so the file has a text segment */
6487 emit_section_change (acfg, ".text", 0);
6488 emit_string (acfg, "");
6490 emit_base_dwarf_info (acfg);
6494 * mono_save_xdebug_info:
6496 * Emit debugging info for METHOD into an assembly file which can be assembled
6497 * and loaded into gdb to provide debugging info for JITted code.
6500 mono_save_xdebug_info (MonoCompile *cfg)
6502 MonoAotCompile *acfg;
6509 mono_acfg_lock (acfg);
6510 emit_method_dwarf_info (acfg, cfg->jit_info->method, NULL, NULL, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
6512 mono_acfg_unlock (acfg);
6516 * mono_save_trampoline_xdebug_info:
6518 * Same as mono_save_xdebug_info, but for trampolines.
6521 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
6523 MonoAotCompile *acfg;
6530 mono_acfg_lock (acfg);
6531 emit_trampoline_dwarf_info (acfg, tramp_name, NULL, NULL, code, code_size, unwind_info);
6533 mono_acfg_unlock (acfg);
6541 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6547 mono_xdebug_init (void)
6552 mono_save_xdebug_info (MonoCompile *cfg)
6557 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)