2007-06-28 Martin Baulig <martin@ximian.com>
[mono.git] / mono / mini / driver.c
1 /*
2  * driver.c: The new mono JIT compiler.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002-2003 Ximian, Inc.
9  * (C) 2003-2006 Novell, Inc.
10  */
11
12 #include <config.h>
13 #include <signal.h>
14 #if HAVE_SCHED_SETAFFINITY
15 #include <sched.h>
16 #endif
17 #ifdef HAVE_UNISTD_H
18 #include <unistd.h>
19 #endif
20
21 #include <mono/metadata/assembly.h>
22 #include <mono/metadata/loader.h>
23 #include <mono/metadata/cil-coff.h>
24 #include <mono/metadata/tabledefs.h>
25 #include <mono/metadata/class.h>
26 #include <mono/metadata/object.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/opcodes.h>
29 #include <mono/metadata/mono-endian.h>
30 #include <mono/metadata/tokentype.h>
31 #include <mono/metadata/tabledefs.h>
32 #include <mono/metadata/threads.h>
33 #include <mono/metadata/marshal.h>
34 #include <mono/metadata/socket-io.h>
35 #include <mono/metadata/appdomain.h>
36 #include <mono/metadata/debug-helpers.h>
37 #include <mono/io-layer/io-layer.h>
38 #include "mono/metadata/profiler.h"
39 #include <mono/metadata/profiler-private.h>
40 #include <mono/metadata/mono-config.h>
41 #include <mono/metadata/environment.h>
42 #include <mono/metadata/verify.h>
43 #include <mono/metadata/mono-debug.h>
44 #include <mono/metadata/security-manager.h>
45 #include <mono/os/gc_wrapper.h>
46 #include "mono/utils/mono-counters.h"
47
48 #include "mini.h"
49 #include "jit.h"
50 #include <string.h>
51 #include <ctype.h>
52 #include "inssel.h"
53 #include <locale.h>
54 #include "version.h"
55
56 static FILE *mini_stats_fd = NULL;
57
58 static void mini_usage (void);
59
60 /* This turns off command line globbing under win32 */
61 #ifdef PLATFORM_WIN32
62 int _CRT_glob = 0;
63 #endif
64
65 typedef void (*OptFunc) (const char *p);
66
67 #undef OPTFLAG
68 #ifdef HAVE_ARRAY_ELEM_INIT
69 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
70 #define MSGSTRFIELD1(line) str##line
71
72 static const struct msgstr_t {
73 #define OPTFLAG(id,shift,name,desc) char MSGSTRFIELD(__LINE__) [sizeof (name) + sizeof (desc)];
74 #include "optflags-def.h"
75 #undef OPTFLAG
76 } opstr = {
77 #define OPTFLAG(id,shift,name,desc) name "\0" desc,
78 #include "optflags-def.h"
79 #undef OPTFLAG
80 };
81 static const gint16 opt_names [] = {
82 #define OPTFLAG(id,shift,name,desc) [(shift)] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
83 #include "optflags-def.h"
84 #undef OPTFLAG
85 };
86
87 #define optflag_get_name(id) ((const char*)&opstr + opt_names [(id)])
88 #define optflag_get_desc(id) (optflag_get_name(id) + 1 + strlen (optflag_get_name(id)))
89
90 #else /* !HAVE_ARRAY_ELEM_INIT */
91 typedef struct {
92         const char* name;
93         const char* desc;
94 } OptName;
95
96 #define OPTFLAG(id,shift,name,desc) {name,desc},
97 static const OptName 
98 opt_names [] = {
99 #include "optflags-def.h"
100         {NULL, NULL}
101 };
102 #define optflag_get_name(id) (opt_names [(id)].name)
103 #define optflag_get_desc(id) (opt_names [(id)].desc)
104
105 #endif
106
107 static const OptFunc
108 opt_funcs [sizeof (int) * 8] = {
109         NULL
110 };
111
112 #define DEFAULT_OPTIMIZATIONS ( \
113         MONO_OPT_PEEPHOLE |     \
114         MONO_OPT_CFOLD |        \
115         MONO_OPT_INLINE |       \
116         MONO_OPT_CONSPROP |     \
117         MONO_OPT_COPYPROP |     \
118         MONO_OPT_TREEPROP |     \
119         MONO_OPT_DEADCE |       \
120         MONO_OPT_BRANCH |       \
121         MONO_OPT_LINEARS |      \
122         MONO_OPT_INTRINS |  \
123         MONO_OPT_LOOP |  \
124         MONO_OPT_EXCEPTION |  \
125         MONO_OPT_AOT)
126
127 #define EXCLUDED_FROM_ALL (MONO_OPT_SHARED | MONO_OPT_PRECOMP)
128
129 static guint32
130 parse_optimizations (const char* p)
131 {
132         /* the default value */
133         guint32 opt = DEFAULT_OPTIMIZATIONS;
134         guint32 exclude = 0;
135         const char *n;
136         int i, invert, len;
137
138         /* call out to cpu detection code here that sets the defaults ... */
139         opt |= mono_arch_cpu_optimizazions (&exclude);
140         opt &= ~exclude;
141         if (!p)
142                 return opt;
143
144         while (*p) {
145                 if (*p == '-') {
146                         p++;
147                         invert = TRUE;
148                 } else {
149                         invert = FALSE;
150                 }
151                 for (i = 0; i < G_N_ELEMENTS (opt_names) && optflag_get_name (i); ++i) {
152                         n = optflag_get_name (i);
153                         len = strlen (n);
154                         if (strncmp (p, n, len) == 0) {
155                                 if (invert)
156                                         opt &= ~ (1 << i);
157                                 else
158                                         opt |= 1 << i;
159                                 p += len;
160                                 if (*p == ',') {
161                                         p++;
162                                         break;
163                                 } else if (*p == '=') {
164                                         p++;
165                                         if (opt_funcs [i])
166                                                 opt_funcs [i] (p);
167                                         while (*p && *p++ != ',');
168                                         break;
169                                 }
170                                 /* error out */
171                                 break;
172                         }
173                 }
174                 if (i == G_N_ELEMENTS (opt_names) || !optflag_get_name (i)) {
175                         if (strncmp (p, "all", 3) == 0) {
176                                 if (invert)
177                                         opt = 0;
178                                 else
179                                         opt = ~(EXCLUDED_FROM_ALL | exclude);
180                                 p += 3;
181                                 if (*p == ',')
182                                         p++;
183                         } else {
184                                 fprintf (stderr, "Invalid optimization name `%s'\n", p);
185                                 exit (1);
186                         }
187                 }
188         }
189         return opt;
190 }
191
192 typedef struct {
193         const char name [6];
194         const char desc [18];
195         MonoGraphOptions value;
196 } GraphName;
197
198 static const GraphName 
199 graph_names [] = {
200         {"cfg",      "Control Flow",                            MONO_GRAPH_CFG},
201         {"dtree",    "Dominator Tree",                          MONO_GRAPH_DTREE},
202         {"code",     "CFG showing code",                        MONO_GRAPH_CFG_CODE},
203         {"ssa",      "CFG after SSA",                           MONO_GRAPH_CFG_SSA},
204         {"optc",     "CFG after IR opts",                       MONO_GRAPH_CFG_OPTCODE}
205 };
206
207 static MonoGraphOptions
208 mono_parse_graph_options (const char* p)
209 {
210         const char *n;
211         int i, len;
212
213         for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
214                 n = graph_names [i].name;
215                 len = strlen (n);
216                 if (strncmp (p, n, len) == 0)
217                         return graph_names [i].value;
218         }
219
220         fprintf (stderr, "Invalid graph name provided: %s\n", p);
221         exit (1);
222 }
223
224 int
225 mono_parse_default_optimizations (const char* p)
226 {
227         guint32 opt;
228
229         opt = parse_optimizations (p);
230         return opt;
231 }
232
233 static char*
234 opt_descr (guint32 flags) {
235         GString *str = g_string_new ("");
236         int i, need_comma;
237
238         need_comma = 0;
239         for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
240                 if (flags & (1 << i)) {
241                         if (need_comma)
242                                 g_string_append_c (str, ',');
243                         g_string_append (str, optflag_get_name (i));
244                         need_comma = 1;
245                 }
246         }
247         return g_string_free (str, FALSE);
248 }
249
250 static const guint32
251 opt_sets [] = {
252        0,
253        MONO_OPT_PEEPHOLE,
254        MONO_OPT_BRANCH,
255        MONO_OPT_CFOLD,
256        MONO_OPT_FCMOV,
257        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS,
258        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS,
259        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP,
260        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_CFOLD,
261        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE,
262        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS,
263        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_SSA,
264        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_EXCEPTION,
265        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_EXCEPTION | MONO_OPT_ABCREM,
266        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_EXCEPTION | MONO_OPT_ABCREM | MONO_OPT_SSAPRE,
267        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_ABCREM,
268        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_TREEPROP,
269        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_SSAPRE,
270        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_ABCREM | MONO_OPT_SHARED
271 };
272
273 typedef int (*TestMethod) (void);
274
275 #if 0
276 static void
277 domain_dump_native_code (MonoDomain *domain) {
278         // need to poke into the domain, move to metadata/domain.c
279         // need to empty jit_info_table and code_mp
280 }
281 #endif
282
283 static int
284 mini_regression (MonoImage *image, int verbose, int *total_run) {
285         guint32 i, opt, opt_flags;
286         MonoMethod *method;
287         MonoCompile *cfg;
288         char *n;
289         int result, expected, failed, cfailed, run, code_size, total;
290         TestMethod func;
291         GTimer *timer = g_timer_new ();
292
293         if (mini_stats_fd) {
294                 fprintf (mini_stats_fd, "$stattitle = \'Mono Benchmark Results (various optimizations)\';\n");
295
296                 fprintf (mini_stats_fd, "$graph->set_legend(qw(");
297                 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); opt++) {
298                         opt_flags = opt_sets [opt];
299                         n = opt_descr (opt_flags);
300                         if (!n [0])
301                                 n = (char *)"none";
302                         if (opt)
303                                 fprintf (mini_stats_fd, " ");
304                         fprintf (mini_stats_fd, "%s", n);
305                 
306
307                 }
308                 fprintf (mini_stats_fd, "));\n");
309
310                 fprintf (mini_stats_fd, "@data = (\n");
311                 fprintf (mini_stats_fd, "[");
312         }
313
314         /* load the metadata */
315         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
316                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
317                 mono_class_init (method->klass);
318
319                 if (!strncmp (method->name, "test_", 5) && mini_stats_fd) {
320                         fprintf (mini_stats_fd, "\"%s\",", method->name);
321                 }
322         }
323         if (mini_stats_fd)
324                 fprintf (mini_stats_fd, "],\n");
325
326
327         total = 0;
328         *total_run = 0;
329         for (opt = 0; opt < G_N_ELEMENTS (opt_sets); ++opt) {
330                 double elapsed, comp_time, start_time;
331
332                 opt_flags = opt_sets [opt];
333                 mono_set_defaults (verbose, opt_flags);
334                 n = opt_descr (opt_flags);
335                 g_print ("Test run: image=%s, opts=%s\n", mono_image_get_filename (image), n);
336                 g_free (n);
337                 cfailed = failed = run = code_size = 0;
338                 comp_time = elapsed = 0.0;
339
340                 /* fixme: ugly hack - delete all previously compiled methods */
341                 g_hash_table_destroy (mono_domain_get ()->jit_trampoline_hash);
342                 mono_domain_get ()->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
343                 mono_internal_hash_table_destroy (&(mono_domain_get ()->jit_code_hash));
344                 mono_jit_code_hash_init (&(mono_domain_get ()->jit_code_hash));
345
346                 g_timer_start (timer);
347                 if (mini_stats_fd)
348                         fprintf (mini_stats_fd, "[");
349                 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
350                         method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
351                         if (strncmp (method->name, "test_", 5) == 0) {
352                                 expected = atoi (method->name + 5);
353                                 run++;
354                                 start_time = g_timer_elapsed (timer, NULL);
355                                 comp_time -= start_time; 
356                                 cfg = mini_method_compile (method, opt_flags, mono_get_root_domain (), TRUE, FALSE, 0);
357                                 comp_time += g_timer_elapsed (timer, NULL);
358                                 if (cfg->exception_type == MONO_EXCEPTION_NONE) {
359                                         if (verbose >= 2)
360                                                 g_print ("Running '%s' ...\n", method->name);
361 #ifdef MONO_USE_AOT_COMPILER
362                                         if ((func = mono_aot_get_method (mono_get_root_domain (), method)))
363                                                 ;
364                                         else
365 #endif
366                                                 func = (TestMethod)(gpointer)cfg->native_code;
367                                         func = (TestMethod)mono_create_ftnptr (mono_get_root_domain (), func);
368                                         result = func ();
369                                         if (result != expected) {
370                                                 failed++;
371                                                 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
372                                         }
373                                         code_size += cfg->code_len;
374                                         mono_destroy_compile (cfg);
375
376                                 } else {
377                                         cfailed++;
378                                         if (verbose)
379                                                 g_print ("Test '%s' failed compilation.\n", method->name);
380                                 }
381                                 if (mini_stats_fd)
382                                         fprintf (mini_stats_fd, "%f, ", 
383                                                  g_timer_elapsed (timer, NULL) - start_time);
384                         }
385                 }
386                 if (mini_stats_fd)
387                         fprintf (mini_stats_fd, "],\n");
388                 g_timer_stop (timer);
389                 elapsed = g_timer_elapsed (timer, NULL);
390                 if (failed > 0 || cfailed > 0){
391                         g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n", 
392                                  run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
393                 } else {
394                         g_print ("Results: total tests: %d, all pass \n",  run);
395                 }
396                 
397                 g_print ("Elapsed time: %f secs (%f, %f), Code size: %d\n\n", elapsed, 
398                          elapsed - comp_time, comp_time, code_size);
399                 total += failed + cfailed;
400                 *total_run += run;
401         }
402
403         if (mini_stats_fd) {
404                 fprintf (mini_stats_fd, ");\n");
405                 fflush (mini_stats_fd);
406         }
407
408         g_timer_destroy (timer);
409         return total;
410 }
411
412 static int
413 mini_regression_list (int verbose, int count, char *images [])
414 {
415         int i, total, total_run, run;
416         MonoAssembly *ass;
417         
418         total_run =  total = 0;
419         for (i = 0; i < count; ++i) {
420                 ass = mono_assembly_open (images [i], NULL);
421                 if (!ass) {
422                         g_warning ("failed to load assembly: %s", images [i]);
423                         continue;
424                 }
425                 total += mini_regression (mono_assembly_get_image (ass), verbose, &run);
426                 total_run += run;
427         }
428         if (total > 0){
429                 g_print ("Overall results: tests: %d, failed: %d, opt combinations: %d (pass: %.2f%%)\n", 
430                          total_run, total, (int)G_N_ELEMENTS (opt_sets), 100.0*(total_run-total)/total_run);
431         } else {
432                 g_print ("Overall results: tests: %d, 100%% pass, opt combinations: %d\n", 
433                          total_run, (int)G_N_ELEMENTS (opt_sets));
434         }
435         
436         return total;
437 }
438
439 enum {
440         DO_BENCH,
441         DO_REGRESSION,
442         DO_COMPILE,
443         DO_EXEC,
444         DO_DRAW,
445         DO_DEBUGGER
446 };
447
448 typedef struct CompileAllThreadArgs {
449         MonoAssembly *ass;
450         int verbose;
451         guint32 opts;
452 } CompileAllThreadArgs;
453
454 static void
455 compile_all_methods_thread_main (CompileAllThreadArgs *args)
456 {
457         MonoAssembly *ass = args->ass;
458         int verbose = args->verbose;
459         MonoImage *image = mono_assembly_get_image (ass);
460         MonoMethod *method;
461         MonoCompile *cfg;
462         int i, count = 0;
463
464         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
465                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
466                 MonoMethodSignature *sig;
467
468                 if (mono_metadata_has_generic_params (image, token))
469                         continue;
470
471                 method = mono_get_method (image, token, NULL);
472                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
473                     (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
474                     (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
475                     (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
476                         continue;
477
478                 if (method->klass->generic_container)
479                         continue;
480                 sig = mono_method_signature (method);
481                 if (sig->has_type_parameters)
482                         continue;
483
484                 count++;
485                 if (verbose) {
486                         char * desc = mono_method_full_name (method, TRUE);
487                         g_print ("Compiling %d %s\n", count, desc);
488                         g_free (desc);
489                 }
490                 cfg = mini_method_compile (method, args->opts, mono_get_root_domain (), FALSE, FALSE, 0);
491                 mono_destroy_compile (cfg);
492         }
493
494 }
495
496 static void
497 compile_all_methods (MonoAssembly *ass, int verbose, guint32 opts)
498 {
499         CompileAllThreadArgs args;
500
501         args.ass = ass;
502         args.verbose = verbose;
503         args.opts = opts;
504
505         /* 
506          * Need to create a mono thread since compilation might trigger
507          * running of managed code.
508          */
509         mono_thread_create (mono_domain_get (), compile_all_methods_thread_main, &args);
510
511         mono_thread_manage ();
512 }
513
514 /**
515  * mono_jit_exec:
516  * @assembly: reference to an assembly
517  * @argc: argument count
518  * @argv: argument vector
519  *
520  * Start execution of a program.
521  */
522 int 
523 mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
524 {
525         MonoImage *image = mono_assembly_get_image (assembly);
526         MonoMethod *method;
527         guint32 entry = mono_image_get_entry_point (image);
528
529         if (!entry) {
530                 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
531                 /* FIXME: remove this silly requirement. */
532                 mono_environment_exitcode_set (1);
533                 return 1;
534         }
535
536         method = mono_get_method (image, entry, NULL);
537         if (method == NULL){
538                 g_print ("The entry point method could not be loaded\n");
539                 mono_environment_exitcode_set (1);
540                 return 1;
541         }
542         
543         return mono_runtime_run_main (method, argc, argv, NULL);
544 }
545
546 typedef struct 
547 {
548         MonoDomain *domain;
549         const char *file;
550         int argc;
551         char **argv;
552         guint32 opts;
553         char *aot_options;
554 } MainThreadArgs;
555
556 static void main_thread_handler (gpointer user_data)
557 {
558         MainThreadArgs *main_args = user_data;
559         MonoAssembly *assembly;
560
561         assembly = mono_domain_assembly_open (main_args->domain, main_args->file);
562         if (!assembly){
563                 fprintf (stderr, "Can not open image %s\n", main_args->file);
564                 exit (1);
565         }
566
567         if (mono_compile_aot) {
568                 int res = mono_compile_assembly (assembly, main_args->opts, main_args->aot_options);
569                 printf ("AOT RESULT %d\n", res);
570         } else {
571                 /* 
572                  * This must be done in a thread managed by mono since it can invoke
573                  * managed code.
574                  */
575                 if (main_args->opts & MONO_OPT_PRECOMP)
576                         mono_precompile_assemblies ();
577
578                 mono_jit_exec (main_args->domain, assembly, main_args->argc, main_args->argv);
579         }
580 }
581
582 static void
583 mini_usage_jitdeveloper (void)
584 {
585         int i;
586         
587         fprintf (stdout,
588                  "Runtime and JIT debugging options:\n"
589                  "    --breakonex            Inserts a breakpoint on exceptions\n"
590                  "    --break METHOD         Inserts a breakpoint at METHOD entry\n"
591                  "    --compile METHOD       Just compile METHOD in assembly\n"
592                  "    --compile-all          Compiles all the methods in the assembly\n"
593                  "    --ncompile N           Number of times to compile METHOD (default: 1)\n"
594                  "    --print-vtable         Print the vtable of all used classes\n"
595                  "    --regression           Runs the regression test contained in the assembly\n"
596                  "    --statfile FILE        Sets the stat file to FILE\n"
597                  "    --stats                Print statistics about the JIT operations\n"
598                  "    --wapi=hps|semdel      IO-layer maintenance\n"
599                  "\n"
600                  "Other options:\n" 
601                  "    --graph[=TYPE] METHOD  Draws a graph of the specified method:\n");
602         
603         for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
604                 fprintf (stdout, "                           %-10s %s\n", graph_names [i].name, graph_names [i].desc);
605         }
606 }
607
608 static void
609 mini_usage_list_opt (void)
610 {
611         int i;
612         
613         for (i = 0; i < G_N_ELEMENTS (opt_names); ++i)
614                 fprintf (stdout, "                           %-10s %s\n", optflag_get_name (i), optflag_get_desc (i));
615 }
616
617 static void
618 mini_usage (void)
619 {
620         fprintf (stdout,
621                 "Usage is: mono [options] program [program-options]\n"
622                 "\n"
623                 "Development:\n"
624                 "    --aot                  Compiles the assembly to native code\n"
625                 "    --debug                Enable debugging support\n"
626                 "    --profile[=profiler]   Runs in profiling mode with the specified profiler module\n"
627                 "    --trace[=EXPR]         Enable tracing, use --help-trace for details\n"
628                 "    --help-devel           Shows more options available to developers\n"
629                 "\n"
630                 "Runtime:\n"
631                 "    --config FILE          Loads FILE as the Mono config\n"
632                 "    --verbose, -v          Increases the verbosity level\n"
633                 "    --help, -h             Show usage information\n"
634                 "    --version, -V          Show version information\n"
635                 "    --runtime=VERSION      Use the VERSION runtime, instead of autodetecting\n"
636                 "    --optimize=OPT         Turns on or off a specific optimization\n"
637                 "                           Use --list-opt to get a list of optimizations\n"
638                 "    --security             Turns on the security manager (unsupported, default is off)\n");
639 }
640
641 static void
642 mini_trace_usage (void)
643 {
644         fprintf (stdout,
645                  "Tracing options:\n"
646                  "   --trace[=EXPR]        Trace every call, optional EXPR controls the scope\n"
647                  "\n"
648                  "EXPR is composed of:\n"
649                  "    all                  All assemblies\n"
650                  "    none                 No assemblies\n"
651                  "    program              Entry point assembly\n"
652                  "    assembly             Specifies an assembly\n"
653                  "    M:Type:Method        Specifies a method\n"
654                  "    N:Namespace          Specifies a namespace\n"
655                  "    T:Type               Specifies a type\n"
656                  "    +EXPR                Includes expression\n"
657                  "    -EXPR                Excludes expression\n"
658                  "    disabled             Don't print any output until toggled via SIGUSR2\n");
659 }
660
661 static const char info[] =
662 #ifdef HAVE_KW_THREAD
663         "\tTLS:           __thread\n"
664 #else
665         "\tTLS:           normal\n"
666 #endif /* HAVE_KW_THREAD */
667         "\tGC:            " USED_GC_NAME "\n"
668 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
669     "\tSIGSEGV:       altstack\n"
670 #else
671     "\tSIGSEGV:       normal\n"
672 #endif
673         "\tArchitecture:  " ARCHITECTURE "\n"
674         "\tDisabled:      " DISABLED_FEATURES "\n"
675         "";
676
677 int
678 mono_main (int argc, char* argv[])
679 {
680         MainThreadArgs main_args;
681         MonoAssembly *assembly;
682         MonoMethodDesc *desc;
683         MonoMethod *method;
684         MonoCompile *cfg;
685         MonoDomain *domain;
686         const char* aname, *mname = NULL;
687         char *config_file = NULL;
688         int i, count = 1;
689         int enable_debugging = FALSE;
690         guint32 opt, action = DO_EXEC;
691         MonoGraphOptions mono_graph_options = 0;
692         int mini_verbose = 0;
693         gboolean enable_profile = FALSE;
694         char *trace_options = NULL;
695         char *profile_options = NULL;
696         char *aot_options = NULL;
697         char *forced_version = NULL;
698
699         setlocale (LC_ALL, "");
700
701 #if HAVE_SCHED_SETAFFINITY
702         if (getenv ("MONO_NO_SMP")) {
703                 unsigned long proc_mask = 1;
704                 sched_setaffinity (getpid(), sizeof (unsigned long), &proc_mask);
705         }
706 #endif
707         if (!g_thread_supported ())
708                 g_thread_init (NULL);
709
710         if (mono_running_on_valgrind () && getenv ("MONO_VALGRIND_LEAK_CHECK")) {
711                 GMemVTable mem_vtable;
712
713                 /* 
714                  * Instruct glib to use the system allocation functions so valgrind
715                  * can track the memory allocated by the g_... functions.
716                  */
717                 memset (&mem_vtable, 0, sizeof (mem_vtable));
718                 mem_vtable.malloc = malloc;
719                 mem_vtable.realloc = realloc;
720                 mem_vtable.free = free;
721                 mem_vtable.calloc = calloc;
722
723                 g_mem_set_vtable (&mem_vtable);
724         }
725
726         g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
727         g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
728
729         opt = parse_optimizations (NULL);
730
731         for (i = 1; i < argc; ++i) {
732                 if (argv [i] [0] != '-')
733                         break;
734                 if (strcmp (argv [i], "--regression") == 0) {
735                         action = DO_REGRESSION;
736                 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
737                         mini_verbose++;
738                 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
739                         g_print ("Mono JIT compiler version %s (%s)\nCopyright (C) 2002-2007 Novell, Inc and Contributors. www.mono-project.com\n", VERSION, FULL_VERSION);
740                         g_print (info);
741                         if (mini_verbose) {
742                                 const char *cerror;
743                                 const char *clibpath;
744                                 mono_init ("mono");
745                                 cerror = mono_check_corlib_version ();
746                                 clibpath = mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown";
747                                 if (cerror) {
748                                         g_print ("The currently installed mscorlib doesn't match this runtime version.\n");
749                                         g_print ("The error is: %s\n", cerror);
750                                         g_print ("mscorlib.dll loaded at: %s\n", clibpath);
751                                         return 1;
752                                 }
753                         }
754                         return 0;
755                 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
756                         mini_usage ();
757                         return 0;
758                 } else if (strcmp (argv [i], "--help-trace") == 0){
759                         mini_trace_usage ();
760                         return 0;
761                 } else if (strcmp (argv [i], "--help-devel") == 0){
762                         mini_usage_jitdeveloper ();
763                         return 0;
764                 } else if (strcmp (argv [i], "--list-opt") == 0){
765                         mini_usage_list_opt ();
766                         return 0;
767                 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
768                         if (i + 1 >= argc){
769                                 fprintf (stderr, "error: --statfile requires a filename argument\n");
770                                 return 1;
771                         }
772                         mini_stats_fd = fopen (argv [++i], "w+");
773                 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
774                         opt = parse_optimizations (argv [i] + 11);
775                 } else if (strncmp (argv [i], "-O=", 3) == 0) {
776                         opt = parse_optimizations (argv [i] + 3);
777                 } else if (strcmp (argv [i], "--config") == 0) {
778                         if (i +1 >= argc){
779                                 fprintf (stderr, "error: --config requires a filename argument\n");
780                                 return 1;
781                         }
782                         config_file = argv [++i];
783                 } else if (strcmp (argv [i], "--ncompile") == 0) {
784                         if (i + 1 >= argc){
785                                 fprintf (stderr, "error: --ncompile requires an argument\n");
786                                 return 1;
787                         }
788                         count = atoi (argv [++i]);
789                         action = DO_BENCH;
790                 } else if (strcmp (argv [i], "--trace") == 0) {
791                         trace_options = (char*)"";
792                 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
793                         trace_options = &argv [i][8];
794                 } else if (strcmp (argv [i], "--breakonex") == 0) {
795                         mono_break_on_exc = TRUE;
796                 } else if (strcmp (argv [i], "--break") == 0) {
797                         if (i+1 >= argc){
798                                 fprintf (stderr, "Missing method name in --break command line option\n");
799                                 return 1;
800                         }
801                         
802                         if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
803                                 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
804                 } else if (strcmp (argv [i], "--print-vtable") == 0) {
805                         mono_print_vtable = TRUE;
806                 } else if (strcmp (argv [i], "--stats") == 0) {
807                         mono_counters_enable (-1);
808                         mono_stats.enabled = TRUE;
809                         mono_jit_stats.enabled = TRUE;
810 #ifndef DISABLE_AOT
811                 } else if (strcmp (argv [i], "--aot") == 0) {
812                         mono_compile_aot = TRUE;
813                 } else if (strncmp (argv [i], "--aot=", 6) == 0) {
814                         mono_compile_aot = TRUE;
815                         aot_options = &argv [i][6];
816 #endif
817                 } else if (strcmp (argv [i], "--compile-all") == 0) {
818                         action = DO_COMPILE;
819                 } else if (strncmp (argv [i], "--runtime=", 10) == 0) {
820                         forced_version = &argv [i][10];
821                 } else if (strcmp (argv [i], "--profile") == 0) {
822                         enable_profile = TRUE;
823                         profile_options = NULL;
824                 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
825                         enable_profile = TRUE;
826                         profile_options = argv [i] + 10;
827                 } else if (strcmp (argv [i], "--compile") == 0) {
828                         if (i + 1 >= argc){
829                                 fprintf (stderr, "error: --compile option requires a method name argument\n");
830                                 return 1;
831                         }
832                         
833                         mname = argv [++i];
834                         action = DO_BENCH;
835                 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
836                         if (i + 1 >= argc){
837                                 fprintf (stderr, "error: --graph option requires a method name argument\n");
838                                 return 1;
839                         }
840                         
841                         mono_graph_options = mono_parse_graph_options (argv [i] + 8);
842                         mname = argv [++i];
843                         action = DO_DRAW;
844                 } else if (strcmp (argv [i], "--graph") == 0) {
845                         if (i + 1 >= argc){
846                                 fprintf (stderr, "error: --graph option requires a method name argument\n");
847                                 return 1;
848                         }
849                         
850                         mname = argv [++i];
851                         mono_graph_options = MONO_GRAPH_CFG;
852                         action = DO_DRAW;
853                 } else if (strcmp (argv [i], "--debug") == 0) {
854                         enable_debugging = TRUE;
855                 } else if (strcmp (argv [i], "--security") == 0) {
856                         mono_use_security_manager = TRUE;
857                         mono_activate_security_manager ();
858                 } else if (strcmp (argv [i], "--desktop") == 0) {
859 #if defined (HAVE_BOEHM_GC)
860                         GC_dont_expand = 1;
861 #endif
862                         /* Put desktop-specific optimizations here */
863                 } else if (strcmp (argv [i], "--server") == 0){
864                         /* Put server-specific optimizations here */
865                 } else if (strcmp (argv [i], "--inside-mdb") == 0) {
866                         action = DO_DEBUGGER;
867                 } else if (strncmp (argv [i], "--wapi=", 7) == 0) {
868                         if (strcmp (argv [i] + 7, "hps") == 0) {
869                                 return mini_wapi_hps (argc - i, argv + i);
870                         } else if (strcmp (argv [i] + 7, "semdel") == 0) {
871                                 return mini_wapi_semdel (argc - i, argv + i);
872                         } else if (strcmp (argv [i] + 7, "seminfo") == 0) {
873                                 return mini_wapi_seminfo (argc - i, argv + i);
874                         } else {
875                                 fprintf (stderr, "Invalid --wapi suboption: '%s'\n", argv [i]);
876                                 return 1;
877                         }
878                 } else {
879                         fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
880                         return 1;
881                 }
882         }
883
884         if (!argv [i]) {
885                 mini_usage ();
886                 return 1;
887         }
888
889         if ((action == DO_EXEC) && g_getenv ("MONO_INSIDE_MDB"))
890                 action = DO_DEBUGGER;
891
892         if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
893                 g_set_prgname (argv[i]);
894         }
895
896         if (enable_profile) {
897                 /* Needed because of TLS accesses in mono_profiler_load () */
898                 MONO_GC_PRE_INIT ();
899                 mono_profiler_load (profile_options);
900         }
901
902         if (trace_options != NULL){
903                 /* 
904                  * Need to call this before mini_init () so we can trace methods 
905                  * compiled there too.
906                  */
907                 mono_jit_trace_calls = mono_trace_parse_options (trace_options);
908                 if (mono_jit_trace_calls == NULL)
909                         exit (1);
910         }
911
912         if (action == DO_DEBUGGER) {
913                 opt |= MONO_OPT_SHARED;
914                 opt &= ~MONO_OPT_INLINE;
915                 opt &= ~MONO_OPT_COPYPROP;
916                 opt &= ~MONO_OPT_CONSPROP;
917                 enable_debugging = TRUE;
918
919 #ifdef MONO_DEBUGGER_SUPPORTED
920                 mono_debug_init (MONO_DEBUG_FORMAT_DEBUGGER);
921                 mono_debugger_init ();
922 #else
923                 g_print ("The Mono Debugger is not supported on this platform.\n");
924                 return 1;
925 #endif
926         }
927
928         mono_set_defaults (mini_verbose, opt);
929         domain = mini_init (argv [i], forced_version);
930         
931         switch (action) {
932         case DO_REGRESSION:
933                 if (mini_regression_list (mini_verbose, argc -i, argv + i)) {
934                         g_print ("Regression ERRORS!\n");
935                         mini_cleanup (domain);
936                         return 1;
937                 }
938                 mini_cleanup (domain);
939                 return 0;
940         case DO_BENCH:
941                 if (argc - i != 1 || mname == NULL) {
942                         g_print ("Usage: mini --ncompile num --compile method assembly\n");
943                         mini_cleanup (domain);
944                         return 1;
945                 }
946                 aname = argv [i];
947                 break;
948         case DO_COMPILE:
949                 if (argc - i != 1) {
950                         mini_usage ();
951                         mini_cleanup (domain);
952                         return 1;
953                 }
954                 aname = argv [i];
955                 break;
956         case DO_DRAW:
957                 if (argc - i != 1 || mname == NULL) {
958                         mini_usage ();
959                         mini_cleanup (domain);
960                         return 1;
961                 }
962                 aname = argv [i];
963                 break;
964         default:
965                 if (argc - i < 1) {
966                         mini_usage ();
967                         mini_cleanup (domain);
968                         return 1;
969                 }
970                 aname = argv [i];
971                 break;
972         }
973
974         if (action == DO_DEBUGGER)
975                 mono_debug_init_1 (domain);
976         else if (enable_debugging) {
977                 mono_debug_init (MONO_DEBUG_FORMAT_MONO);
978                 mono_debug_init_1 (domain);
979         }
980
981         /* Parse gac loading options before loading assemblies. */
982         if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
983                 mono_config_parse (config_file);
984         }
985
986         assembly = mono_assembly_open (aname, NULL);
987         if (!assembly) {
988                 fprintf (stderr, "Cannot open assembly %s.\n", aname);
989                 mini_cleanup (domain);
990                 return 2;
991         }
992
993         if (trace_options != NULL)
994                 mono_trace_set_assembly (assembly);
995
996         if (enable_debugging)
997                 mono_debug_init_2 (assembly);
998
999         if (mono_compile_aot || action == DO_EXEC) {
1000                 const char *error;
1001
1002                 //mono_set_rootdir ();
1003
1004                 error = mono_check_corlib_version ();
1005                 if (error) {
1006                         fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
1007                         fprintf (stderr, "Loaded from: %s\n",
1008                                 mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown");
1009                         fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.go-mono.com/daily.\n");
1010                         exit (1);
1011                 }
1012
1013 #ifdef PLATFORM_WIN32
1014                 /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
1015                 if (!enable_debugging && !mono_compile_aot && ((MonoCLIImageInfo*)(mono_assembly_get_image (assembly)->image_info))->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
1016                         FreeConsole ();
1017 #endif
1018
1019                 main_args.domain = domain;
1020                 main_args.file = aname;         
1021                 main_args.argc = argc - i;
1022                 main_args.argv = argv + i;
1023                 main_args.opts = opt;
1024                 main_args.aot_options = aot_options;
1025 #if RUN_IN_SUBTHREAD
1026                 mono_runtime_exec_managed_code (domain, main_thread_handler, &main_args);
1027 #else
1028                 main_thread_handler (&main_args);
1029                 mono_thread_manage ();
1030 #endif
1031                 mini_cleanup (domain);
1032
1033                 /* Look up return value from System.Environment.ExitCode */
1034                 i = mono_environment_exitcode_get ();
1035                 return i;
1036         } else if (action == DO_COMPILE) {
1037                 compile_all_methods (assembly, mini_verbose, opt);
1038                 mini_cleanup (domain);
1039                 return 0;
1040         } else if (action == DO_DEBUGGER) {
1041 #ifdef MONO_DEBUGGER_SUPPORTED
1042                 const char *error;
1043
1044                 error = mono_check_corlib_version ();
1045                 if (error) {
1046                         fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
1047                         fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.go-mono.com/daily.\n");
1048                         exit (1);
1049                 }
1050
1051                 mono_debugger_main (domain, assembly, argc - i, argv + i);
1052                 mini_cleanup (domain);
1053                 return 0;
1054 #else
1055                 return 1;
1056 #endif
1057         }
1058         desc = mono_method_desc_new (mname, 0);
1059         if (!desc) {
1060                 g_print ("Invalid method name %s\n", mname);
1061                 mini_cleanup (domain);
1062                 return 3;
1063         }
1064         method = mono_method_desc_search_in_image (desc, mono_assembly_get_image (assembly));
1065         if (!method) {
1066                 g_print ("Cannot find method %s\n", mname);
1067                 mini_cleanup (domain);
1068                 return 3;
1069         }
1070
1071         if (action == DO_DRAW) {
1072                 int part = 0;
1073
1074                 switch (mono_graph_options) {
1075                 case MONO_GRAPH_DTREE:
1076                         part = 1;
1077                         opt |= MONO_OPT_LOOP;
1078                         break;
1079                 case MONO_GRAPH_CFG_CODE:
1080                         part = 1;
1081                         break;
1082                 case MONO_GRAPH_CFG_SSA:
1083                         part = 2;
1084                         break;
1085                 case MONO_GRAPH_CFG_OPTCODE:
1086                         part = 3;
1087                         break;
1088                 default:
1089                         break;
1090                 }
1091
1092                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1093                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
1094                         MonoMethod *nm;
1095                         nm = mono_marshal_get_native_wrapper (method);
1096                         cfg = mini_method_compile (nm, opt, mono_get_root_domain (), FALSE, FALSE, part);
1097                 }
1098                 else
1099                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, part);
1100                 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
1101                         g_warning ("no SSA info available (use -O=deadce)");
1102                         return 1;
1103                 }
1104                 mono_draw_graph (cfg, mono_graph_options);
1105                 mono_destroy_compile (cfg);
1106
1107         } else if (action == DO_BENCH) {
1108                 if (mini_stats_fd) {
1109                         const char *n;
1110                         double no_opt_time = 0.0;
1111                         GTimer *timer = g_timer_new ();
1112                         fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n", 
1113                                  mono_method_full_name (method, TRUE));
1114                         fprintf (mini_stats_fd, "@data = (\n");
1115                         fprintf (mini_stats_fd, "[");
1116                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
1117                                 opt = opt_sets [i];
1118                                 n = opt_descr (opt);
1119                                 if (!n [0])
1120                                         n = "none";
1121                                 fprintf (mini_stats_fd, "\"%s\",", n);
1122                         }
1123                         fprintf (mini_stats_fd, "],\n[");
1124
1125                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
1126                                 int j;
1127                                 double elapsed;
1128                                 opt = opt_sets [i];
1129                                 g_timer_start (timer);
1130                                 for (j = 0; j < count; ++j) {
1131                                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1132                                         mono_destroy_compile (cfg);
1133                                 }
1134                                 g_timer_stop (timer);
1135                                 elapsed = g_timer_elapsed (timer, NULL);
1136                                 if (!opt)
1137                                         no_opt_time = elapsed;
1138                                 fprintf (mini_stats_fd, "%f, ", elapsed);
1139                         }
1140                         fprintf (mini_stats_fd, "]");
1141                         if (no_opt_time > 0.0) {
1142                                 fprintf (mini_stats_fd, ", \n[");
1143                                 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) 
1144                                         fprintf (mini_stats_fd, "%f,", no_opt_time);
1145                                 fprintf (mini_stats_fd, "]");
1146                         }
1147                         fprintf (mini_stats_fd, ");\n");
1148                 } else {
1149                         for (i = 0; i < count; ++i) {
1150                                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1151                                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
1152                                         method = mono_marshal_get_native_wrapper (method);
1153
1154                                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1155                                 mono_destroy_compile (cfg);
1156                         }
1157                 }
1158         } else {
1159                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1160                 mono_destroy_compile (cfg);
1161         }
1162
1163         mini_cleanup (domain);
1164         return 0;
1165 }
1166
1167 MonoDomain * 
1168 mono_jit_init (const char *file)
1169 {
1170         return mini_init (file, NULL);
1171 }
1172
1173 MonoDomain * 
1174 mono_jit_init_version (const char *file, const char *runtime_version)
1175 {
1176         return mini_init (file, runtime_version);
1177 }
1178
1179 void        
1180 mono_jit_cleanup (MonoDomain *domain)
1181 {
1182         mini_cleanup (domain);
1183 }