2004-11-07 Ben Maurer <bmaurer@ximian.com>
[mono.git] / mono / mini / aot.c
1 /*
2  * aot.c: mono Ahead of Time compiler
3  *
4  * Author:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *
7  * (C) 2002 Ximian, Inc.
8  */
9
10 #include "config.h"
11 #include <sys/types.h>
12 #include <unistd.h>
13 #include <fcntl.h>
14 #include <string.h>
15 #ifndef PLATFORM_WIN32
16 #include <sys/mman.h>
17 #else
18 #include <windows.h>
19 #endif
20
21 #include <errno.h>
22 #include <sys/stat.h>
23 #include <limits.h>    /* for PAGESIZE */
24 #ifndef PAGESIZE
25 #define PAGESIZE 4096
26 #endif
27
28 #include <mono/metadata/tabledefs.h>
29 #include <mono/metadata/class.h>
30 #include <mono/metadata/object.h>
31 #include <mono/metadata/tokentype.h>
32 #include <mono/metadata/appdomain.h>
33 #include <mono/metadata/debug-helpers.h>
34 #include <mono/metadata/assembly.h>
35 #include <mono/metadata/metadata-internals.h>
36 #include <mono/metadata/marshal.h>
37 #include <mono/utils/mono-logger.h>
38 #include <mono/os/gc_wrapper.h>
39
40 #include "mini.h"
41
42 #ifdef PLATFORM_WIN32
43 #define SHARED_EXT ".dll"
44 #elif defined(__ppc__) && defined(__MACH__)
45 #define SHARED_EXT ".dylib"
46 #else
47 #define SHARED_EXT ".so"
48 #endif
49
50 #if defined(sparc) || defined(__ppc__)
51 #define AS_STRING_DIRECTIVE ".asciz"
52 #else
53 /* GNU as */
54 #define AS_STRING_DIRECTIVE ".string"
55 #endif
56
57 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
58
59 typedef struct MonoAotMethod {
60         MonoJitInfo *info;
61         MonoJumpInfo *patch_info;
62         MonoDomain *domain;
63 } MonoAotMethod;
64
65 typedef struct MonoAotModule {
66         /* Optimization flags used to compile the module */
67         guint32 opts;
68         /* Maps MonoMethods to MonoAotMethodInfos */
69         MonoGHashTable *methods;
70         char **icall_table;
71         MonoImage **image_table;
72         guint32* methods_present_table;
73 } MonoAotModule;
74
75 typedef struct MonoAotCompile {
76         FILE *fp;
77         GHashTable *ref_hash;
78         GHashTable *icall_hash;
79         GPtrArray *icall_table;
80         GHashTable *image_hash;
81         GPtrArray *image_table;
82 } MonoAotCompile;
83
84 typedef struct MonoAotOptions {
85         char *outfile;
86 } MonoAotOptions;
87
88 static MonoGHashTable *aot_modules;
89
90 static CRITICAL_SECTION aot_mutex;
91
92 /*
93  * Disabling this will make a copy of the loaded code and use the copy instead 
94  * of the original. This will place the caller and the callee close to each 
95  * other in memory, possibly improving cache behavior. Since the original
96  * code is in copy-on-write memory, this will not increase the memory usage
97  * of the runtime.
98  */
99 static gboolean use_loaded_code = FALSE;
100
101 /*
102  * Whenever to AOT compile loaded assemblies on demand and store them in
103  * a cache under $HOME/.mono/aot-cache.
104  */
105 static gboolean use_aot_cache = FALSE;
106
107 /* For debugging */
108 static gint32 mono_last_aot_method = -1;
109
110 static MonoJitInfo*
111 mono_aot_load_method (MonoDomain *domain, MonoAotModule *aot_module, MonoMethod *method, guint8 *code, guint8 *info);
112
113 static MonoClass*
114 decode_klass_info (MonoAotModule *module, guint32 *info, guint32 **out_info)
115 {
116         MonoImage *image;
117         MonoClass *klass;
118         guint32 token, rank;
119
120         image = module->image_table [info [0]];
121         token = info [1];
122         info += 2;
123         if (token) {
124                 klass = mono_class_get (image, token);
125         } else {
126                 token = info [0];
127                 rank = info [1];
128                 info += 2;
129                 klass = mono_class_get (image, token);
130                 g_assert (klass);
131                 klass = mono_array_class_get (klass, rank);
132         }
133         g_assert (klass);
134         mono_class_init (klass);
135
136         *out_info = info;
137         return klass;
138 }
139
140 static MonoClassField*
141 decode_field_info (MonoAotModule *module, guint32 *info, guint32 **out_info)
142 {
143         MonoClass *klass = decode_klass_info (module, info, &info);
144         guint32 token;
145
146         token = info [0];
147         info ++;
148         *out_info = info;
149
150         return mono_class_get_field (klass, token);
151 }
152
153 static void
154 create_cache_structure (void)
155 {
156         const char *home;
157         char *tmp;
158         int err;
159
160         home = g_get_home_dir ();
161         if (!home)
162                 return;
163
164         tmp = g_build_filename (home, ".mono", NULL);
165         if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
166                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
167 #ifdef PLATFORM_WIN32
168                 err = mkdir (tmp);
169 #else
170                 err = mkdir (tmp, 0777);
171 #endif
172                 if (err) {
173                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
174                         g_free (tmp);
175                         return;
176                 }
177         }
178         g_free (tmp);
179         tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
180         if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
181                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
182 #ifdef PLATFORM_WIN32
183                 err = mkdir (tmp);
184 #else
185                 err = mkdir (tmp, 0777);
186 #endif
187                 if (err) {
188                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
189                         g_free (tmp);
190                         return;
191                 }
192         }
193         g_free (tmp);
194 }
195
196 /*
197  * load_aot_module_from_cache:
198  *
199  *  Experimental code to AOT compile loaded assemblies on demand. 
200  *
201  * FIXME: 
202  * - Add environment variable MONO_AOT_CACHE_OPTIONS
203  * - Add options for controlling the cache size
204  * - Handle full cache by deleting old assemblies lru style
205  * - Add options for excluding assemblies during development
206  * - Maybe add a threshold after an assembly is AOT compiled
207  * - invoking a new mono process is a security risk
208  */
209 static GModule*
210 load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
211 {
212         char *fname, *cmd, *tmp2;
213         const char *home;
214         GModule *module;
215         gboolean res;
216         gchar *out, *err;
217
218         *aot_name = NULL;
219
220         if (assembly->image->dynamic)
221                 return NULL;
222
223         create_cache_structure ();
224
225         home = g_get_home_dir ();
226
227         tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
228         fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
229         *aot_name = fname;
230         g_free (tmp2);
231
232         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
233         module = g_module_open (fname, G_MODULE_BIND_LAZY);     
234
235         if (!module) {
236                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");
237
238                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);
239
240                 /* FIXME: security */
241                 cmd = g_strdup_printf ("mono -O=all --aot=outfile=%s %s", fname, assembly->image->name);
242
243                 res = g_spawn_command_line_sync (cmd, &out, &err, NULL, NULL);
244                 g_free (cmd);
245                 if (!res) {
246                         mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
247                         return NULL;
248                 }
249
250                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
251
252                 module = g_module_open (fname, G_MODULE_BIND_LAZY);     
253         }
254
255         return module;
256 }
257
258 static void
259 load_aot_module (MonoAssembly *assembly, gpointer user_data)
260 {
261         char *aot_name;
262         MonoAotModule *info;
263         gboolean usable = TRUE;
264         char *saved_guid = NULL;
265         char *aot_version = NULL;
266         char *opt_flags = NULL;
267
268         if (mono_compile_aot)
269                 return;
270                                                         
271         if (use_aot_cache)
272                 assembly->aot_module = load_aot_module_from_cache (assembly, &aot_name);
273         else {
274                 aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
275
276                 assembly->aot_module = g_module_open (aot_name, G_MODULE_BIND_LAZY);
277
278                 if (!assembly->aot_module) {
279                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, g_module_error ());
280                 }
281         }
282
283         if (!assembly->aot_module) {
284                 g_free (aot_name);
285                 return;
286         }
287
288         g_module_symbol (assembly->aot_module, "mono_assembly_guid", (gpointer *) &saved_guid);
289         g_module_symbol (assembly->aot_module, "mono_aot_version", (gpointer *) &aot_version);
290         g_module_symbol (assembly->aot_module, "mono_aot_opt_flags", (gpointer *)&opt_flags);
291
292         if (!aot_version || strcmp (aot_version, MONO_AOT_FILE_VERSION)) {
293                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s has wrong file format version (expected %s got %s)\n", aot_name, MONO_AOT_FILE_VERSION, aot_version);
294                 usable = FALSE;
295         }
296         else
297                 if (!saved_guid || strcmp (assembly->image->guid, saved_guid)) {
298                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date.\n", aot_name);
299                         usable = FALSE;
300                 }
301
302         if (!usable) {
303                 g_free (aot_name);
304                 g_module_close (assembly->aot_module);
305                 assembly->aot_module = NULL;
306                 return;
307         }
308
309         /*
310          * It seems that MonoGHashTables are in the GC heap, so structures
311          * containing them must be in the GC heap as well :(
312          */
313 #ifdef HAVE_BOEHM_GC
314         info = GC_MALLOC (sizeof (MonoAotModule));
315 #else
316         info = g_new0 (MonoAotModule, 1);
317 #endif
318         info->methods = mono_g_hash_table_new (NULL, NULL);
319         sscanf (opt_flags, "%d", &info->opts);
320
321         /* Read image table */
322         {
323                 guint32 table_len, i;
324                 char *table = NULL;
325
326                 g_module_symbol (assembly->aot_module, "mono_image_table", (gpointer *)&table);
327                 g_assert (table);
328
329                 table_len = *(guint32*)table;
330                 table += sizeof (guint32);
331                 info->image_table = g_new0 (MonoImage*, table_len);
332                 for (i = 0; i < table_len; ++i) {
333                         info->image_table [i] = mono_image_loaded_by_guid (table);
334                         if (!info->image_table [i]) {
335                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date.\n", aot_name);
336                                 mono_g_hash_table_destroy (info->methods);
337                                 g_free (info->image_table);
338 #ifndef HAVE_BOEHM_GC
339                                 g_free (info);
340 #endif
341                                 g_free (aot_name);
342                                 g_module_close (assembly->aot_module);
343                                 assembly->aot_module = NULL;
344                                 return;
345                         }
346                         table += strlen (table) + 1;
347                 }
348         }
349
350         /* Read icall table */
351         {
352                 guint32 table_len, i;
353                 char *table = NULL;
354
355                 g_module_symbol (assembly->aot_module, "mono_icall_table", (gpointer *)&table);
356                 g_assert (table);
357
358                 table_len = *(guint32*)table;
359                 table += sizeof (guint32);
360                 info->icall_table = g_new0 (char*, table_len);
361                 for (i = 0; i < table_len; ++i) {
362                         info->icall_table [i] = table;
363                         table += strlen (table) + 1;
364                 }
365         }
366
367         /* Read methods present table */
368         g_module_symbol (assembly->aot_module, "mono_methods_present_table", (gpointer *)&info->methods_present_table);
369         g_assert (info->methods_present_table);
370
371         EnterCriticalSection (&aot_mutex);
372         mono_g_hash_table_insert (aot_modules, assembly, info);
373         LeaveCriticalSection (&aot_mutex);
374
375         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
376 }
377
378 void
379 mono_aot_init (void)
380 {
381         InitializeCriticalSection (&aot_mutex);
382
383         MONO_GC_REGISTER_ROOT (aot_modules);
384         aot_modules = mono_g_hash_table_new (NULL, NULL);
385
386         mono_install_assembly_load_hook (load_aot_module, NULL);
387
388         if (getenv ("MONO_LASTAOT"))
389                 mono_last_aot_method = atoi (getenv ("MONO_LASTAOT"));
390 }
391  
392 static MonoJitInfo *
393 mono_aot_get_method_inner (MonoDomain *domain, MonoMethod *method)
394 {
395         MonoClass *klass = method->klass;
396         MonoAssembly *ass = klass->image->assembly;
397         GModule *module = ass->aot_module;
398         char method_label [256];
399         char info_label [256];
400         guint8 *code = NULL;
401         guint8 *info;
402         MonoAotModule *aot_module;
403         MonoAotMethod *minfo;
404         MonoJitInfo *jinfo;
405         MonoMethodHeader *header;
406         int i;
407
408         if (!module)
409                 return NULL;
410
411         if (!method->token)
412                 return NULL;
413
414         if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
415                 return NULL;
416
417         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
418                 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
419                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
420                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
421                 return NULL;
422         
423         header = mono_method_get_header (method);
424         
425         aot_module = (MonoAotModule*)mono_g_hash_table_lookup (aot_modules, ass);
426
427         g_assert (klass->inited);
428
429         minfo = mono_g_hash_table_lookup (aot_module->methods, method);
430         /* Can't use code from non-root domains since they can be unloaded */
431         if (minfo && (minfo->domain == mono_get_root_domain ())) {
432                 /* This method was already loaded in another appdomain */
433
434                 /* Duplicate jinfo */
435                 jinfo = mono_mempool_alloc0 (domain->mp, sizeof (MonoJitInfo));
436                 memcpy (jinfo, minfo->info, sizeof (MonoJitInfo));
437                 if (jinfo->clauses) {
438                         jinfo->clauses = 
439                                 mono_mempool_alloc0 (domain->mp, sizeof (MonoJitExceptionInfo) * header->num_clauses);
440                         memcpy (jinfo->clauses, minfo->info->clauses, sizeof (MonoJitExceptionInfo) * header->num_clauses);
441                 }
442
443                 if (aot_module->opts & MONO_OPT_SHARED)
444                         /* Use the same method in the new appdomain */
445                         ;
446                 else if (!minfo->patch_info)
447                         /* Use the same method in the new appdomain */
448                         ;                       
449                 else {
450                         /* Create a copy of the original method and apply relocations */
451
452                         code = mono_code_manager_reserve (domain->code_mp, minfo->info->code_size);
453                         memcpy (code, minfo->info->code_start, minfo->info->code_size);
454
455                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT REUSE METHOD: %s %p - %p.\n", mono_method_full_name (method, TRUE), code, (char*)code + minfo->info->code_size);
456
457                         /* Do this outside the lock to avoid deadlocks */
458                         LeaveCriticalSection (&aot_mutex);
459                         mono_arch_patch_code (method, domain, code, minfo->patch_info, TRUE);
460                         EnterCriticalSection (&aot_mutex);
461                         mono_arch_flush_icache (code, minfo->info->code_size);
462
463                         /* Relocate jinfo */
464                         jinfo->code_start = code;
465                         if (jinfo->clauses) {
466                                 for (i = 0; i < header->num_clauses; ++i) {
467                                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
468                                         gint32 offset = code - (guint8*)minfo->info->code_start;
469
470                                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
471                                                 ei->data.filter = (guint8*)ei->data.filter + offset;
472                                         ei->try_start = (guint8*)ei->try_start + offset;
473                                         ei->try_end = (guint8*)ei->try_end + offset;
474                                         ei->handler_start = (guint8*)ei->handler_start + offset;
475                                 }
476                         }
477                 }
478
479                 return jinfo;
480         }
481
482         /* Do a fast check to see whenever the method exists */
483         {
484                 guint32 index = mono_metadata_token_index (method->token) - 1;
485                 guint32 w;
486                 w = aot_module->methods_present_table [index / 32];
487                 if (! (w & (1 << (index % 32)))) {
488                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", mono_method_full_name (method, TRUE));
489                         return NULL;
490                 }
491         }
492
493         sprintf (method_label, "m_%x", mono_metadata_token_index (method->token));
494
495         if (!g_module_symbol (module, method_label, (gpointer *)&code))
496                 return NULL;
497
498         sprintf (info_label, "%s_p", method_label);
499
500         if (!g_module_symbol (module, info_label, (gpointer *)&info))
501                 return NULL;
502
503         if (mono_last_aot_method != -1) {
504                 if (mono_jit_stats.methods_aot > mono_last_aot_method)
505                                 return NULL;
506                 else
507                         if (mono_jit_stats.methods_aot == mono_last_aot_method)
508                                 printf ("LAST AOT METHOD: %s.%s.%s.\n", klass->name_space, klass->name, method->name);
509         }
510
511         return mono_aot_load_method (domain, aot_module, method, code, info);
512 }
513
514 static MonoJitInfo*
515 mono_aot_load_method (MonoDomain *domain, MonoAotModule *aot_module, MonoMethod *method, guint8 *code, guint8 *info)
516 {
517         MonoClass *klass = method->klass;
518         MonoJumpInfo *patch_info = NULL;
519         guint code_len, used_int_regs, used_strings;
520         MonoAotMethod *minfo;
521         MonoJitInfo *jinfo;
522         MonoMethodHeader *header = mono_method_get_header (method);
523         GPtrArray *patches;
524         int i, pindex;
525
526         minfo = g_new0 (MonoAotMethod, 1);
527
528         minfo->domain = domain;
529         jinfo = mono_mempool_alloc0 (domain->mp, sizeof (MonoJitInfo));
530
531         code_len = *(guint32*)info;
532         info += 4;
533         used_int_regs = *(guint32*)info;
534         info += 4;
535
536         if (!use_loaded_code) {
537                 guint8 *code2;
538                 code2 = mono_code_manager_reserve (domain->code_mp, code_len);
539                 memcpy (code2, code, code_len);
540                 mono_arch_flush_icache (code2, code_len);
541                 code = code2;
542         }
543
544         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND AOT compiled code for %s %p - %p %p\n", mono_method_full_name (method, TRUE), code, code + code_len, info);
545
546         /* Exception table */
547         if (header->num_clauses) {
548                 jinfo->clauses = 
549                         mono_mempool_alloc0 (domain->mp, sizeof (MonoJitExceptionInfo) * header->num_clauses);
550                 jinfo->num_clauses = header->num_clauses;
551
552                 jinfo->exvar_offset = *(guint32*)info;
553                 info += 4;
554
555                 for (i = 0; i < header->num_clauses; ++i) {
556                         MonoExceptionClause *ec = &header->clauses [i];                         
557                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
558
559                         ei->flags = ec->flags;
560                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
561                                 ei->data.filter = code + *(guint32*)info;
562                         else
563                                 ei->data.token = *(guint32*)info;
564                         info += 4;
565                         ei->try_start = code + *(guint32*)info;
566                         info += 4;
567                         ei->try_end = code + *(guint32*)info;
568                         info += 4;
569                         ei->handler_start = code + *(guint32*)info;
570                         info += 4;
571                 }
572         }
573
574         if (aot_module->opts & MONO_OPT_SHARED) {
575                 used_strings = *(guint32*)info;
576                 info += 4;
577         }
578         else
579                 used_strings = 0;
580
581         for (i = 0; i < used_strings; i++) {
582                 guint token =  *(guint32*)info;
583                 info += 4;
584                 mono_ldstr (mono_get_root_domain (), klass->image, mono_metadata_token_index (token));
585         }
586
587         if (*info) {
588                 MonoMemPool *mp;
589                 MonoImage *image;
590                 guint8 *page_start;
591                 gpointer *table;
592                 int pages;
593                 int i, err;
594                 guint32 last_offset, buf_len;
595                 guint32 *info32;
596
597                 if (aot_module->opts & MONO_OPT_SHARED)
598                         mp = mono_mempool_new ();
599                 else
600                         mp = domain->mp;
601
602                 /* First load the type + offset table */
603                 last_offset = 0;
604                 patches = g_ptr_array_new ();
605                 while (*info) {
606                         MonoJumpInfo *ji = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
607
608                         guint8 b1, b2;
609
610                         b1 = *(guint8*)info;
611                         b2 = *((guint8*)info + 1);
612                         
613                         info += 2;
614
615                         ji->type = b1 >> 2;
616
617                         if (((b1 & (1 + 2)) == 3) && (b2 == 255)) {
618                                 info = ALIGN_PTR_TO (info, 4);
619                                 ji->ip.i = *(guint32*)info;
620                                 info += 4;
621                         }
622                         else
623                                 ji->ip.i = (((guint32)(b1 & (1 + 2))) << 8) + b2;
624
625                         ji->ip.i += last_offset;
626                         last_offset = ji->ip.i;
627                         //printf ("T: %d O: %d.\n", ji->type, ji->ip.i);
628
629                         ji->next = patch_info;
630                         patch_info = ji;
631
632                         g_ptr_array_add (patches, ji);
633                 }
634                 info ++;
635
636                 info = ALIGN_PTR_TO (info, sizeof (gpointer));
637
638                 info32 = (guint32*)info;
639
640                 /* Then load the other data */
641                 for (pindex = 0; pindex < patches->len; ++pindex) {
642                         MonoJumpInfo *ji = g_ptr_array_index (patches, pindex);
643
644                         switch (ji->type) {
645                         case MONO_PATCH_INFO_CLASS:
646                         case MONO_PATCH_INFO_IID:
647                         case MONO_PATCH_INFO_VTABLE:
648                         case MONO_PATCH_INFO_CLASS_INIT:
649                                 ji->data.klass = decode_klass_info (aot_module, info32, &info32);
650                                 break;
651                         case MONO_PATCH_INFO_IMAGE:
652                                 ji->data.image = aot_module->image_table [info32 [0]];
653                                 g_assert (ji->data.image);
654                                 info32 ++;
655                                 break;
656                         case MONO_PATCH_INFO_METHOD:
657                         case MONO_PATCH_INFO_METHODCONST:
658                         case MONO_PATCH_INFO_METHOD_JUMP: {
659                                 guint32 image_index, token;
660
661                                 image_index = info32 [0] >> 24;
662                                 token = MONO_TOKEN_METHOD_DEF | (info32 [0] & 0xffffff);
663
664                                 image = aot_module->image_table [image_index];
665                                 ji->data.method = mono_get_method (image, token, NULL);
666                                 g_assert (ji->data.method);
667                                 mono_class_init (ji->data.method->klass);
668                                 info32 ++;
669
670                                 break;
671                         }
672                         case MONO_PATCH_INFO_WRAPPER: {
673                                 guint32 wrapper_type;
674
675                                 wrapper_type = info32 [0];
676                                 info32 ++;
677
678                                 switch (wrapper_type) {
679                                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
680                                         guint32 image_index, token;
681
682                                         image_index = info32 [0] >> 24;
683                                         token = MONO_TOKEN_METHOD_DEF | (info32 [0] & 0xffffff);
684
685                                         image = aot_module->image_table [image_index];
686                                         ji->data.method = mono_get_method (image, token, NULL);
687                                         g_assert (ji->data.method);
688                                         mono_class_init (ji->data.method->klass);
689
690                                         ji->type = MONO_PATCH_INFO_METHOD;
691                                         ji->data.method = mono_marshal_get_remoting_invoke_with_check (ji->data.method);
692                                         info32 ++;
693                                         break;
694                                 }
695                                 case MONO_WRAPPER_PROXY_ISINST: {
696                                         MonoClass *klass = decode_klass_info (aot_module, info32, &info32);
697
698                                         ji->type = MONO_PATCH_INFO_METHODCONST;
699                                         ji->data.method = mono_marshal_get_proxy_cancast (klass);
700                                         break;
701                                 }
702                                 case MONO_WRAPPER_LDFLD:
703                                 case MONO_WRAPPER_STFLD: {
704                                         MonoClass *klass = decode_klass_info (aot_module, info32, &info32);
705
706                                         ji->type = MONO_PATCH_INFO_METHOD;
707                                         if (wrapper_type == MONO_WRAPPER_LDFLD)
708                                                 ji->data.method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
709                                         else
710                                                 ji->data.method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
711                                         break;
712                                 }
713                                 default:
714                                         g_assert_not_reached ();
715                                 }
716                                 break;
717                         }
718                         case MONO_PATCH_INFO_FIELD:
719                         case MONO_PATCH_INFO_SFLDA:
720                                 ji->data.field = decode_field_info (aot_module, info32, &info32);
721                                 break;
722                         case MONO_PATCH_INFO_INTERNAL_METHOD:
723                                 ji->data.name = aot_module->icall_table [info32 [0]];
724                                 g_assert (ji->data.name);
725                                 info32 ++;
726                                 //printf ("A: %s.\n", ji->data.name);
727                                 break;
728                         case MONO_PATCH_INFO_SWITCH:
729                                 ji->table_size = info32 [0];
730                                 table = g_new (gpointer, ji->table_size);
731                                 ji->data.target = table;
732                                 for (i = 0; i < ji->table_size; i++) {
733                                         table [i] = (gpointer)(gssize)info32 [i + 1];
734                                 }
735                                 info32 += (ji->table_size + 1);
736                                 break;
737                         case MONO_PATCH_INFO_R4:
738                                 ji->data.target = info32;
739                                 info32 ++;
740                                 break;
741                         case MONO_PATCH_INFO_R8:
742                                 info32 = ALIGN_PTR_TO (info32, 8);
743                                 ji->data.target = info32;
744                                 info32 += 2;
745                                 break;
746                         case MONO_PATCH_INFO_LDSTR:
747                         case MONO_PATCH_INFO_LDTOKEN:
748                         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
749                                 image = aot_module->image_table [info32 [0]];
750                                 ji->data.token = mono_jump_info_token_new (mp, image, info32 [1]);
751                                 info32 += 2;
752                                 break;
753                         case MONO_PATCH_INFO_EXC_NAME:
754                                 ji->data.klass = decode_klass_info (aot_module, info32, &info32);
755                                 ji->data.name = ji->data.klass->name;
756                                 break;
757                         case MONO_PATCH_INFO_METHOD_REL:
758                                 ji->data.offset = info32 [0];
759                                 info32 ++;
760                                 break;
761                         default:
762                                 g_warning ("unhandled type %d", ji->type);
763                                 g_assert_not_reached ();
764                         }
765                 }
766
767                 info = (guint8*)info32;
768
769                 g_ptr_array_free (patches, TRUE);
770
771                 buf_len = *(guint32*)info;
772                 info += 4;
773                 mono_debug_add_aot_method (domain, method, code, info, buf_len);
774
775                 if (use_loaded_code) {
776                 /* disable write protection */
777 #ifndef PLATFORM_WIN32
778                         page_start = (char *) (((gssize) (code)) & ~ (PAGESIZE - 1));
779                         pages = (code + code_len - page_start + PAGESIZE - 1) / PAGESIZE;
780                         err = mprotect (page_start, pages * PAGESIZE, PROT_READ | PROT_WRITE | PROT_EXEC);
781                         g_assert (err == 0);
782 #else
783                         {
784                                 DWORD oldp;
785                                 g_assert (VirtualProtect (code, code_len, PAGE_EXECUTE_READWRITE, &oldp) != 0);
786                         }
787 #endif
788                 }
789
790                 /* Do this outside the lock to avoid deadlocks */
791                 LeaveCriticalSection (&aot_mutex);
792                 mono_arch_patch_code (method, domain, code, patch_info, TRUE);
793                 EnterCriticalSection (&aot_mutex);
794
795                 if (aot_module->opts & MONO_OPT_SHARED)
796                         /* No need to cache patches */
797                         mono_mempool_destroy (mp);
798                 else
799                         minfo->patch_info = patch_info;
800         }
801
802         mono_jit_stats.methods_aot++;
803
804         {
805                 jinfo->code_size = code_len;
806                 jinfo->used_regs = used_int_regs;
807                 jinfo->method = method;
808                 jinfo->code_start = code;
809                 jinfo->domain_neutral = (aot_module->opts & MONO_OPT_SHARED) != 0;
810
811                 minfo->info = jinfo;
812                 mono_g_hash_table_insert (aot_module->methods, method, minfo);
813
814                 return jinfo;
815         }
816 }
817
818 MonoJitInfo*
819 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
820 {
821         MonoJitInfo *info;
822
823         EnterCriticalSection (&aot_mutex);
824         info = mono_aot_get_method_inner (domain, method);
825         LeaveCriticalSection (&aot_mutex);
826
827         /* Do this outside the lock */
828         if (info) {
829                 mono_jit_info_table_add (domain, info);
830                 return info;
831         }
832         else
833                 return NULL;
834 }
835
836 static void
837 emit_section_change (FILE *fp, const char *section_name, int subsection_index)
838 {
839 #if defined(sparc)
840         /* For solaris as, GNU as should accept the same */
841         fprintf (fp, ".section \"%s\"\n", section_name);
842 #elif defined(__ppc__) && defined(__MACH__)
843         /* This needs to be made more precise on mach. */
844         fprintf (fp, "%s\n", subsection_index == 0 ? ".text" : ".data");
845 #else
846         fprintf (fp, "%s %d\n", section_name, subsection_index);
847 #endif
848 }
849
850 static void
851 emit_global (FILE *fp, const char *name)
852 {
853 #if defined(__ppc__) && defined(__MACH__)
854     // mach-o always uses a '_' prefix.
855         fprintf (fp, ".globl _%s\n", name);
856 #else
857         fprintf (fp, ".globl %s\n", name);
858 #endif
859 }
860
861 static void
862 emit_label (FILE *fp, const char *name)
863 {
864 #if defined(__ppc__) && defined(__MACH__)
865     // mach-o always uses a '_' prefix.
866         fprintf (fp, "_%s:\n", name);
867 #else
868         fprintf (fp, "%s:\n", name);
869 #endif
870 }
871
872 #if 0
873 static void
874 write_data_symbol (FILE *fp, const char *name, guint8 *buf, int size, int align)
875 {
876         int i;
877
878         emit_section_change (fp, ".text", 1);
879
880         fprintf (fp, ".globl %s\n", name);
881         fprintf (fp, "\t.align %d\n", align);
882         fprintf (fp, "\t.type %s,#object\n", name);
883         fprintf (fp, "\t.size %s,%d\n", name, size);
884         fprintf (fp, "%s:\n", name);
885         for (i = 0; i < size; i++) { 
886                 fprintf (fp, ".byte %d\n", buf [i]);
887         }
888         
889 }
890 #endif
891
892 static void
893 write_string_symbol (FILE *fp, const char *name, const char *value)
894 {
895         emit_section_change (fp, ".text", 1);
896         emit_global(fp, name);
897         emit_label(fp, name);
898         fprintf (fp, "\t%s \"%s\"\n", AS_STRING_DIRECTIVE, value);
899 }
900
901 static guint32
902 mono_get_field_token (MonoClassField *field) 
903 {
904         MonoClass *klass = field->parent;
905         int i;
906
907         for (i = 0; i < klass->field.count; ++i) {
908                 if (field == &klass->fields [i])
909                         return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
910         }
911
912         g_assert_not_reached ();
913         return 0;
914 }
915
916 static guint32
917 get_image_index (MonoAotCompile *cfg, MonoImage *image)
918 {
919         guint32 index;
920
921         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
922         if (index)
923                 return index - 1;
924         else {
925                 index = g_hash_table_size (cfg->image_hash);
926                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
927                 g_ptr_array_add (cfg->image_table, image);
928                 return index;
929         }
930 }
931
932 static void
933 emit_klass_info (MonoAotCompile *cfg, MonoClass *klass)
934 {
935         fprintf (cfg->fp, "\t.long 0x%08x\n", get_image_index (cfg, klass->image));
936         fprintf (cfg->fp, "\t.long 0x%08x\n", klass->type_token);
937         if (!klass->type_token) {
938                 /* Array class */
939                 g_assert (klass->rank > 0);
940                 g_assert (klass->element_class->type_token);
941                 fprintf (cfg->fp, "\t.long 0x%08x\n", klass->element_class->type_token);
942                 fprintf (cfg->fp, "\t.long 0x%08x\n", klass->rank);
943         }
944 }
945
946 static void
947 emit_field_info (MonoAotCompile *cfg, MonoClassField *field)
948 {
949         emit_klass_info (cfg, field->parent);
950         fprintf (cfg->fp, "\t.long 0x%08x\n", mono_get_field_token (field));
951 }
952
953 #if defined(__ppc__) && defined(__MACH__)
954 static int
955 ilog2(register int value)
956 {
957     int count = -1;
958     while (value & ~0xf) count += 4, value >>= 4;
959     while (value) count++, value >>= 1;
960     return count;
961 }
962 #endif
963
964 static void 
965 emit_alignment(FILE *fp, int size)
966 {
967 #if defined(__ppc__) && defined(__MACH__)
968         // the mach-o assembler specifies alignments as powers of 2.
969         fprintf (fp, "\t.align %d\t; ilog2\n", ilog2(size));
970 #elif defined(__powerpc__)
971         /* ignore on linux/ppc */
972 #else
973         fprintf (fp, "\t.align %d\n", size);
974 #endif
975 }
976
977 G_GNUC_UNUSED static void
978 emit_pointer (FILE *fp, const char *target)
979 {
980         emit_alignment (fp, sizeof (gpointer));
981 #if defined(__x86_64__)
982         fprintf (fp, "\t.quad %s\n", target);
983 #elif defined(sparc) && SIZEOF_VOID_P == 8
984         fprintf (fp, "\t.xword %s\n", target);
985 #else
986         fprintf (fp, "\t.long %s\n", target);
987 #endif
988 }
989
990 static gint
991 compare_patches (gconstpointer a, gconstpointer b)
992 {
993         int i, j;
994
995         i = (*(MonoJumpInfo**)a)->ip.i;
996         j = (*(MonoJumpInfo**)b)->ip.i;
997
998         if (i < j)
999                 return -1;
1000         else
1001                 if (i > j)
1002                         return 1;
1003         else
1004                 return 0;
1005 }
1006
1007 static void
1008 emit_method (MonoAotCompile *acfg, MonoCompile *cfg)
1009 {
1010         MonoMethod *method;
1011         GList *l;
1012         FILE *tmpfp;
1013         int i, j, k, pindex;
1014         guint8 *code, *mname, *mname_p;
1015         int func_alignment = 16;
1016         GPtrArray *patches;
1017         MonoJumpInfo *patch_info;
1018         MonoMethodHeader *header;
1019         guint32 last_offset;
1020
1021         tmpfp = acfg->fp;
1022         method = cfg->method;
1023         code = cfg->native_code;
1024         header = mono_method_get_header (method);
1025
1026         emit_section_change (tmpfp, ".text", 0);
1027         mname = g_strdup_printf ("m_%x", mono_metadata_token_index (method->token));
1028         mname_p = g_strdup_printf ("%s_p", mname);
1029         emit_alignment(tmpfp, func_alignment);
1030         emit_global(tmpfp, mname);
1031 #if defined(sparc)
1032         fprintf (tmpfp, "\t.type %s,#function\n", mname);
1033 #elif !(defined(__ppc__) && defined(__MACH__))
1034         fprintf (tmpfp, "\t.type %s,@function\n", mname);
1035 #endif
1036         emit_label(tmpfp, mname);
1037
1038         for (i = 0; i < cfg->code_len; i++) 
1039                 fprintf (tmpfp, ".byte %d\n", (unsigned int) code [i]);
1040
1041         emit_section_change (tmpfp, ".text", 1);
1042
1043         /* Sort relocations */
1044         patches = g_ptr_array_new ();
1045         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
1046                 g_ptr_array_add (patches, patch_info);
1047         g_ptr_array_sort (patches, compare_patches);
1048
1049         emit_global (tmpfp, mname_p);
1050         emit_alignment (tmpfp, sizeof (gpointer));
1051         emit_label (tmpfp, mname_p);
1052
1053         fprintf (tmpfp, "\t.long %d\n", cfg->code_len);
1054         fprintf (tmpfp, "\t.long %ld\n", (long)cfg->used_int_regs);
1055
1056         /* Exception table */
1057         if (header->num_clauses) {
1058                 MonoJitInfo *jinfo = cfg->jit_info;
1059
1060                 fprintf (tmpfp, "\t.long %d\n", jinfo->exvar_offset);
1061
1062                 for (k = 0; k < header->num_clauses; ++k) {
1063                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
1064
1065                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
1066                                 fprintf (tmpfp, "\t.long %d\n", (gint)((guint8*)ei->data.filter - code));
1067                         else
1068                                 /* fixme: tokens are not global */
1069                                 fprintf (tmpfp, "\t.long %d\n", ei->data.token);
1070
1071                         fprintf (tmpfp, "\t.long %d\n", (gint)((guint8*)ei->try_start - code));
1072                         fprintf (tmpfp, "\t.long %d\n", (gint)((guint8*)ei->try_end - code));
1073                         fprintf (tmpfp, "\t.long %d\n", (gint)((guint8*)ei->handler_start - code));
1074                 }
1075         }
1076
1077         /* String table */
1078         if (cfg->opt & MONO_OPT_SHARED) {
1079                 fprintf (tmpfp, "\t.long %d\n", g_list_length (cfg->ldstr_list));
1080                 for (l = cfg->ldstr_list; l; l = l->next) {
1081                         fprintf (tmpfp, "\t.long 0x%08lx\n", (long)l->data);
1082                 }
1083         }
1084         else
1085                 /* Used only in shared mode */
1086                 g_assert (!cfg->ldstr_list);
1087
1088         //printf ("M: %s (%s).\n", mono_method_full_name (method, TRUE), mname);
1089
1090         /* First emit the type+position table */
1091         last_offset = 0;
1092         j = 0;
1093         for (pindex = 0; pindex < patches->len; ++pindex) {
1094                 guint32 offset;
1095                 patch_info = g_ptr_array_index (patches, pindex);
1096                 
1097                 if ((patch_info->type == MONO_PATCH_INFO_LABEL) ||
1098                         (patch_info->type == MONO_PATCH_INFO_BB))
1099                         /* Nothing to do */
1100                         continue;
1101
1102                 j ++;
1103                 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
1104                 offset = patch_info->ip.i - last_offset;
1105                 last_offset = patch_info->ip.i;
1106
1107                 /* Encode type+position compactly */
1108                 g_assert (patch_info->type < 64);
1109                 if (offset < 1024 - 1) {
1110                         fprintf (tmpfp, "\t.byte %d\n", (patch_info->type << 2) + (offset >> 8));
1111                         fprintf (tmpfp, "\t.byte %d\n", offset & ((1 << 8) - 1));
1112                 }
1113                 else {
1114                         fprintf (tmpfp, "\t.byte %d\n", (patch_info->type << 2) + 3);
1115                         fprintf (tmpfp, "\t.byte %d\n", 255);
1116                         emit_alignment(tmpfp, 4);
1117                         fprintf (tmpfp, "\t.long %d\n", offset);
1118                 }
1119         }
1120
1121         if (j) {
1122                 /*
1123                  * 0 is PATCH_INFO_BB, which can't be in the file.
1124                  */
1125                 /* NULL terminated array */
1126                 fprintf (tmpfp, "\t.byte 0\n");
1127
1128                 emit_alignment (tmpfp, sizeof (gpointer));
1129
1130                 /* Then emit the other info */
1131                 for (pindex = 0; pindex < patches->len; ++pindex) {
1132                         patch_info = g_ptr_array_index (patches, pindex);
1133
1134                         if ((patch_info->type == MONO_PATCH_INFO_LABEL) ||
1135                                 (patch_info->type == MONO_PATCH_INFO_BB))
1136                                 /* Nothing to do */
1137                                 continue;
1138
1139                         switch (patch_info->type) {
1140                         case MONO_PATCH_INFO_LABEL:
1141                         case MONO_PATCH_INFO_BB:
1142                                 break;
1143                         case MONO_PATCH_INFO_IMAGE:
1144                                 fprintf (tmpfp, "\t.long 0x%08x\n", get_image_index (acfg, patch_info->data.image));
1145                                 break;
1146                         case MONO_PATCH_INFO_METHOD_REL:
1147                                 fprintf (tmpfp, "\t.long 0x%08x\n", (gint)patch_info->data.offset);
1148                                 break;
1149                         case MONO_PATCH_INFO_SWITCH: {
1150                                 gpointer *table = (gpointer *)patch_info->data.target;
1151                                 int k;
1152
1153                                 fprintf (tmpfp, "\t.long %d\n", patch_info->table_size);
1154                         
1155                                 for (k = 0; k < patch_info->table_size; k++) {
1156                                         fprintf (tmpfp, "\t.long %d\n", (int)(gssize)table [k]);
1157                                 }
1158                                 break;
1159                         }
1160                         case MONO_PATCH_INFO_METHODCONST:
1161                         case MONO_PATCH_INFO_METHOD:
1162                         case MONO_PATCH_INFO_METHOD_JUMP: {
1163                                 guint32 image_index = get_image_index (acfg, patch_info->data.method->klass->image);
1164                                 guint32 token = patch_info->data.method->token;
1165                                 g_assert (image_index < 256);
1166                                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1167
1168                                 fprintf (tmpfp, "\t.long 0x%08x\n", (image_index << 24) + (mono_metadata_token_index (token)));
1169                                 break;
1170                         }
1171                         case MONO_PATCH_INFO_INTERNAL_METHOD: {
1172                                 guint32 icall_index;
1173
1174                                 icall_index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->icall_hash, patch_info->data.name));
1175                                 if (!icall_index) {
1176                                         icall_index = g_hash_table_size (acfg->icall_hash) + 1;
1177                                         g_hash_table_insert (acfg->icall_hash, (gpointer)patch_info->data.name,
1178                                                                                  GUINT_TO_POINTER (icall_index));
1179                                         g_ptr_array_add (acfg->icall_table, (gpointer)patch_info->data.name);
1180                                 }
1181                                 fprintf (tmpfp, "\t.long 0x%08x\n", icall_index - 1);
1182                                 break;
1183                         }
1184                         case MONO_PATCH_INFO_LDSTR:
1185                         case MONO_PATCH_INFO_LDTOKEN:
1186                         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1187                                 fprintf (tmpfp, "\t.long 0x%08x\n", get_image_index (acfg, patch_info->data.token->image));
1188                                 fprintf (tmpfp, "\t.long 0x%08x\n", patch_info->data.token->token);
1189                                 break;
1190                         case MONO_PATCH_INFO_EXC_NAME: {
1191                                 MonoClass *ex_class;
1192
1193                                 ex_class =
1194                                         mono_class_from_name (mono_defaults.exception_class->image,
1195                                                                                   "System", patch_info->data.target);
1196                                 g_assert (ex_class);
1197                                 emit_klass_info (acfg, ex_class);
1198                                 break;
1199                         }
1200                         case MONO_PATCH_INFO_R4:
1201                                 fprintf (tmpfp, "\t.long 0x%08x\n", *((guint32 *)patch_info->data.target));     
1202                                 break;
1203                         case MONO_PATCH_INFO_R8:
1204                                 emit_alignment (tmpfp, 8);
1205                                 fprintf (tmpfp, "\t.long 0x%08x\n", *((guint32 *)patch_info->data.target));
1206                                 fprintf (tmpfp, "\t.long 0x%08x\n", *(((guint32 *)patch_info->data.target) + 1));
1207                                 break;
1208                         case MONO_PATCH_INFO_VTABLE:
1209                         case MONO_PATCH_INFO_CLASS_INIT:
1210                         case MONO_PATCH_INFO_CLASS:
1211                         case MONO_PATCH_INFO_IID:
1212                                 emit_klass_info (acfg, patch_info->data.klass);
1213                                 break;
1214                         case MONO_PATCH_INFO_FIELD:
1215                         case MONO_PATCH_INFO_SFLDA:
1216                                 emit_field_info (acfg, patch_info->data.field);
1217                                 break;
1218                         case MONO_PATCH_INFO_WRAPPER: {
1219                                 fprintf (tmpfp, "\t.long %d\n", patch_info->data.method->wrapper_type);
1220
1221                                 switch (patch_info->data.method->wrapper_type) {
1222                                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
1223                                         MonoMethod *m;
1224                                         guint32 image_index;
1225                                         guint32 token;
1226
1227                                         m = mono_marshal_method_from_wrapper (patch_info->data.method);
1228                                         image_index = get_image_index (acfg, m->klass->image);
1229                                         token = m->token;
1230                                         g_assert (image_index < 256);
1231                                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1232
1233                                         fprintf (tmpfp, "\t.long %d\n", (image_index << 24) + (mono_metadata_token_index (token)));
1234                                         break;
1235                                 }
1236                                 case MONO_WRAPPER_PROXY_ISINST:
1237                                 case MONO_WRAPPER_LDFLD:
1238                                 case MONO_WRAPPER_STFLD: {
1239                                         MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (patch_info->data.method);
1240                                         emit_klass_info (acfg, proxy_class);
1241                                         break;
1242                                 }
1243                                 default:
1244                                         g_assert_not_reached ();
1245                                 }
1246                                 break;
1247                         }
1248                         default:
1249                                 g_warning ("unable to handle jump info %d", patch_info->type);
1250                                 g_assert_not_reached ();
1251                         }
1252                 }
1253         }
1254
1255         {
1256                 guint8 *buf;
1257                 guint32 buf_len;
1258
1259                 mono_debug_serialize_debug_info (cfg, &buf, &buf_len);
1260
1261                 fprintf (tmpfp, "\t.long %d\n", buf_len);
1262
1263                 for (i = 0; i < buf_len; ++i)
1264                         fprintf (tmpfp, ".byte %d\n", (unsigned int) buf [i]);
1265
1266                 if (buf_len > 0)
1267                         g_free (buf);
1268         }
1269
1270         /* fixme: save the rest of the required infos */
1271
1272         g_free (mname);
1273         g_free (mname_p);
1274 }
1275
1276 static gboolean
1277 str_begins_with (const char *str1, const char *str2)
1278 {
1279         int len = strlen (str2);
1280         return strncmp (str1, str2, len) == 0;
1281 }
1282
1283 static void
1284 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
1285 {
1286         gchar **args, **ptr;
1287
1288         memset (opts, 0, sizeof (*opts));
1289
1290         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
1291         for (ptr = args; ptr && *ptr; ptr ++) {
1292                 const char *arg = *ptr;
1293
1294                 if (str_begins_with (arg, "outfile=")) {
1295                         opts->outfile = g_strdup (arg + strlen ("outfile="));
1296                 }
1297                 else {
1298                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
1299                         exit (1);
1300                 }
1301         }
1302 }
1303
1304 int
1305 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
1306 {
1307         MonoCompile *cfg;
1308         MonoImage *image = ass->image;
1309         MonoMethod *method;
1310         char *com, *tmpfname, *opts_str;
1311         FILE *tmpfp;
1312         int i;
1313         guint8 *symbol;
1314         int ccount = 0, mcount = 0, lmfcount = 0, abscount = 0, wrappercount = 0, ocount = 0;
1315         GHashTable *ref_hash;
1316         MonoAotCompile *acfg;
1317         gboolean *emitted;
1318         MonoAotOptions aot_opts;
1319         char *outfile_name, *tmp_outfile_name;
1320
1321         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
1322
1323         mono_aot_parse_options (aot_options, &aot_opts);
1324
1325         i = g_file_open_tmp ("mono_aot_XXXXXX", &tmpfname, NULL);
1326         tmpfp = fdopen (i, "w+");
1327         g_assert (tmpfp);
1328
1329         ref_hash = g_hash_table_new (NULL, NULL);
1330
1331         acfg = g_new0 (MonoAotCompile, 1);
1332         acfg->fp = tmpfp;
1333         acfg->ref_hash = ref_hash;
1334         acfg->icall_hash = g_hash_table_new (NULL, NULL);
1335         acfg->icall_table = g_ptr_array_new ();
1336         acfg->image_hash = g_hash_table_new (NULL, NULL);
1337         acfg->image_table = g_ptr_array_new ();
1338
1339         write_string_symbol (tmpfp, "mono_assembly_guid" , image->guid);
1340
1341         write_string_symbol (tmpfp, "mono_aot_version", MONO_AOT_FILE_VERSION);
1342
1343         opts_str = g_strdup_printf ("%d", opts);
1344         write_string_symbol (tmpfp, "mono_aot_opt_flags", opts_str);
1345         g_free (opts_str);
1346
1347         emitted = g_new0 (gboolean, image->tables [MONO_TABLE_METHOD].rows);
1348
1349         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
1350                 MonoJumpInfo *patch_info;
1351                 gboolean skip;
1352                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1353                 method = mono_get_method (image, token, NULL);
1354                 
1355                 /* fixme: maybe we can also precompile wrapper methods */
1356                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1357                     (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1358                     (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1359                     (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
1360                         //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
1361                         continue;
1362                 }
1363
1364                 mcount++;
1365
1366                 /* fixme: we need to patch the IP for the LMF in that case */
1367                 if (method->save_lmf) {
1368                         //printf ("Skip (needs lmf):  %s\n", mono_method_full_name (method, TRUE));
1369                         lmfcount++;
1370                         continue;
1371                 }
1372
1373                 //printf ("START:           %s\n", mono_method_full_name (method, TRUE));
1374                 //mono_compile_method (method);
1375
1376                 cfg = mini_method_compile (method, opts, mono_get_root_domain (), FALSE, 0);
1377                 g_assert (cfg);
1378
1379                 if (cfg->disable_aot) {
1380                         printf ("Skip (other): %s\n", mono_method_full_name (method, TRUE));
1381                         ocount++;
1382                         continue;
1383                 }
1384
1385                 skip = FALSE;
1386                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
1387                         if (patch_info->type == MONO_PATCH_INFO_ABS) {
1388                                 /* unable to handle this */
1389                                 //printf ("Skip (abs addr):   %s %d\n", mono_method_full_name (method, TRUE), patch_info->type);
1390                                 skip = TRUE;    
1391                                 break;
1392                         }
1393                 }
1394
1395                 if (skip) {
1396                         abscount++;
1397                         continue;
1398                 }
1399
1400                 /* some wrappers are very common */
1401                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
1402                         if (patch_info->type == MONO_PATCH_INFO_METHODCONST) {
1403                                 switch (patch_info->data.method->wrapper_type) {
1404                                 case MONO_WRAPPER_PROXY_ISINST:
1405                                         patch_info->type = MONO_PATCH_INFO_WRAPPER;
1406                                 }
1407                         }
1408
1409                         if (patch_info->type == MONO_PATCH_INFO_METHOD) {
1410                                 switch (patch_info->data.method->wrapper_type) {
1411                                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1412                                 case MONO_WRAPPER_STFLD:
1413                                 case MONO_WRAPPER_LDFLD:
1414                                         patch_info->type = MONO_PATCH_INFO_WRAPPER;
1415                                         break;
1416                                 }
1417                         }
1418                 }
1419
1420                 skip = FALSE;
1421                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
1422                         if ((patch_info->type == MONO_PATCH_INFO_METHOD ||
1423                              patch_info->type == MONO_PATCH_INFO_METHODCONST)) {
1424                                 if (patch_info->data.method->wrapper_type) {
1425                                         /* unable to handle this */
1426                                         //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));
1427                                         skip = TRUE;
1428                                         break;
1429                                 }
1430                                 if (!patch_info->data.method->token) {
1431                                         /*
1432                                          * The method is part of a constructed type like Int[,].Set (). It doesn't
1433                                          * have a token, and we can't make one, since the parent type is part of
1434                                          * assembly which contains the element type, and not the assembly which
1435                                          * referenced this type.
1436                                          */
1437                                         skip = TRUE;
1438                                         break;
1439                                 }
1440                         }
1441                 }
1442
1443                 if (skip) {
1444                         wrappercount++;
1445                         continue;
1446                 }
1447
1448                 //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
1449
1450                 emitted [i] = TRUE;
1451                 emit_method (acfg, cfg);
1452
1453                 mono_destroy_compile (cfg);
1454
1455                 ccount++;
1456         }
1457
1458         /*
1459          * The icall and image tables are small but referenced in a lot of places.
1460          * So we emit them at once, and reference their elements by an index
1461          * instead of an assembly label to cut back on the number of relocations.
1462          */
1463
1464         /* Emit icall table */
1465
1466         symbol = g_strdup_printf ("mono_icall_table");
1467         emit_section_change (tmpfp, ".text", 1);
1468         emit_global(tmpfp, symbol);
1469         emit_alignment(tmpfp, 8);
1470         emit_label(tmpfp, symbol);
1471         fprintf (tmpfp, ".long %d\n", acfg->icall_table->len);
1472         for (i = 0; i < acfg->icall_table->len; i++)
1473                 fprintf (tmpfp, "%s \"%s\"\n", AS_STRING_DIRECTIVE, (char*)g_ptr_array_index (acfg->icall_table, i));
1474
1475         /* Emit image table */
1476
1477         symbol = g_strdup_printf ("mono_image_table");
1478         emit_section_change (tmpfp, ".text", 1);
1479         emit_global(tmpfp, symbol);
1480         emit_alignment(tmpfp, 8);
1481         emit_label(tmpfp, symbol);
1482         fprintf (tmpfp, ".long %d\n", acfg->image_table->len);
1483         for (i = 0; i < acfg->image_table->len; i++)
1484                 fprintf (tmpfp, "%s \"%s\"\n", AS_STRING_DIRECTIVE, ((MonoImage*)g_ptr_array_index (acfg->image_table, i))->guid);
1485
1486         /*
1487          * g_module_symbol takes a lot of time for failed lookups, so we emit
1488          * a table which contains one bit for each method. This bit specifies
1489          * whenever the method is emitted or not.
1490          */
1491
1492         symbol = g_strdup_printf ("mono_methods_present_table");
1493         emit_section_change (tmpfp, ".text", 1);
1494         emit_global(tmpfp, symbol);
1495         emit_alignment(tmpfp, 8);
1496         emit_label(tmpfp, symbol);
1497         {
1498                 guint32 k, nrows;
1499                 guint32 w;
1500
1501                 nrows = image->tables [MONO_TABLE_METHOD].rows;
1502                 for (i = 0; i < nrows / 32 + 1; ++i) {
1503                         w = 0;
1504                         for (k = 0; k < 32; ++k) {
1505                                 if (emitted [(i * 32) + k])
1506                                         w += (1 << k);
1507                         }
1508                         //printf ("EMITTED [%d] = %d.\n", i, b);
1509                         fprintf (tmpfp, "\t.long %d\n", w);
1510                 }
1511         }
1512
1513         fclose (tmpfp);
1514
1515 #if defined(__x86_64__)
1516         com = g_strdup_printf ("as --64 %s -o %s.o", tmpfname, tmpfname);
1517 #elif defined(sparc) && SIZEOF_VOID_P == 8
1518         com = g_strdup_printf ("as -xarch=v9 %s -o %s.o", tmpfname, tmpfname);
1519 #else
1520         com = g_strdup_printf ("as %s -o %s.o", tmpfname, tmpfname);
1521 #endif
1522         printf ("Executing the native assembler: %s\n", com);
1523         if (system (com) != 0) {
1524                 g_free (com);
1525                 return 1;
1526         }
1527
1528         g_free (com);
1529
1530         if (aot_opts.outfile)
1531                 outfile_name = g_strdup_printf ("%s", aot_opts.outfile);
1532         else
1533                 outfile_name = g_strdup_printf ("%s%s", image->name, SHARED_EXT);
1534
1535         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
1536
1537 #if defined(sparc)
1538         com = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, tmpfname);
1539 #elif defined(__ppc__) && defined(__MACH__)
1540         com = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, tmpfname);
1541 #else
1542         com = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, tmpfname);
1543 #endif
1544         printf ("Executing the native linker: %s\n", com);
1545         if (system (com) != 0) {
1546                 g_free (tmp_outfile_name);
1547                 g_free (outfile_name);
1548                 g_free (com);
1549                 return 1;
1550         }
1551
1552         g_free (com);
1553         com = g_strdup_printf ("%s.o", tmpfname);
1554         unlink (com);
1555         g_free (com);
1556         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", image->name, SHARED_EXT);
1557         printf ("Stripping the binary: %s\n", com);
1558         system (com);
1559         g_free (com);*/
1560
1561         rename (tmp_outfile_name, outfile_name);
1562
1563         g_free (tmp_outfile_name);
1564         g_free (outfile_name);
1565
1566         printf ("Compiled %d out of %d methods (%d%%)\n", ccount, mcount, mcount ? (ccount*100)/mcount : 100);
1567         printf ("%d methods contain absolute addresses (%d%%)\n", abscount, mcount ? (abscount*100)/mcount : 100);
1568         printf ("%d methods contain wrapper references (%d%%)\n", wrappercount, mcount ? (wrappercount*100)/mcount : 100);
1569         printf ("%d methods contain lmf pointers (%d%%)\n", lmfcount, mcount ? (lmfcount*100)/mcount : 100);
1570         printf ("%d methods have other problems (%d%%)\n", ocount, mcount ? (ocount*100)/mcount : 100);
1571         //printf ("Retained input file.\n");
1572         unlink (tmpfname);
1573
1574         return 0;
1575 }
1576
1577