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