merge from trunk revisions 58933, 58935, 58936
[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/mono-debug-debugger.h>
40 #include <mono/metadata/security-manager.h>
41 #include <mono/os/gc_wrapper.h>
42
43 #include "mini.h"
44 #include "jit.h"
45 #include <string.h>
46 #include <ctype.h>
47 #include "inssel.h"
48 #include <locale.h>
49
50 static FILE *mini_stats_fd = NULL;
51
52 static void mini_usage (void);
53
54 /* This turns off command line globbing under win32 */
55 #ifdef PLATFORM_WIN32
56 int _CRT_glob = 0;
57 #endif
58
59 typedef void (*OptFunc) (const char *p);
60
61 /* keep in sync with enum in mini.h */
62 typedef struct {
63         const char* name;
64         const char* desc;
65         const OptFunc func;
66 } OptName;
67
68 static const OptName 
69 opt_names [] = {
70         {"peephole",   "Peephole postpass"},
71         {"branch",     "Branch optimizations"},
72         {"inline",     "Inline method calls"},
73         {"cfold",      "Constant folding"},
74         {"consprop",   "Constant propagation"},
75         {"copyprop",   "Copy propagation"},
76         {"deadce",     "Dead code elimination"},
77         {"linears",    "Linear scan global reg allocation"},
78         {"cmov",       "Conditional moves"},
79         {"shared",     "Emit per-domain code"},
80         {"sched",      "Instruction scheduling"},
81         {"intrins",    "Intrinsic method implementations"},
82         {"tailc",      "Tail recursion and tail calls"},
83         {"loop",       "Loop related optimizations"},
84         {"fcmov",      "Fast x86 FP compares"},
85         {"leaf",       "Leaf procedures optimizations"},
86         {"aot",        "Usage of Ahead Of Time compiled code"},
87         {"precomp",    "Precompile all methods before executing Main"},
88         {"abcrem",     "Array bound checks removal"},   
89         {"ssapre",     "SSA based Partial Redundancy Elimination"},
90         {"exception",  "Optimize exception catch blocks"},
91         {"ssa",        "Build and use SSA form"}
92 };
93
94 #define DEFAULT_OPTIMIZATIONS ( \
95         MONO_OPT_PEEPHOLE |     \
96         MONO_OPT_CFOLD |        \
97         MONO_OPT_BRANCH |       \
98         MONO_OPT_LINEARS |      \
99         MONO_OPT_INTRINS |  \
100         MONO_OPT_LOOP |  \
101         MONO_OPT_EXCEPTION |  \
102         MONO_OPT_AOT)
103
104 #define EXCLUDED_FROM_ALL (MONO_OPT_SHARED | MONO_OPT_PRECOMP)
105
106 static guint32
107 parse_optimizations (const char* p)
108 {
109         /* the default value */
110         guint32 opt = DEFAULT_OPTIMIZATIONS;
111         guint32 exclude = 0;
112         const char *n;
113         int i, invert, len;
114
115         /* call out to cpu detection code here that sets the defaults ... */
116         opt |= mono_arch_cpu_optimizazions (&exclude);
117         opt &= ~exclude;
118         if (!p)
119                 return opt;
120
121         while (*p) {
122                 if (*p == '-') {
123                         p++;
124                         invert = TRUE;
125                 } else {
126                         invert = FALSE;
127                 }
128                 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
129                         n = opt_names [i].name;
130                         len = strlen (n);
131                         if (strncmp (p, n, len) == 0) {
132                                 if (invert)
133                                         opt &= ~ (1 << i);
134                                 else
135                                         opt |= 1 << i;
136                                 p += len;
137                                 if (*p == ',') {
138                                         p++;
139                                         break;
140                                 } else if (*p == '=') {
141                                         p++;
142                                         if (opt_names [i].func)
143                                                 opt_names [i].func (p);
144                                         while (*p && *p++ != ',');
145                                         break;
146                                 }
147                                 /* error out */
148                                 break;
149                         }
150                 }
151                 if (i == G_N_ELEMENTS (opt_names)) {
152                         if (strncmp (p, "all", 3) == 0) {
153                                 if (invert)
154                                         opt = 0;
155                                 else
156                                         opt = ~(EXCLUDED_FROM_ALL | exclude);
157                                 p += 3;
158                                 if (*p == ',')
159                                         p++;
160                         } else {
161                                 fprintf (stderr, "Invalid optimization name `%s'\n", p);
162                                 exit (1);
163                         }
164                 }
165         }
166         return opt;
167 }
168
169 typedef struct {
170         const char* name;
171         const char* desc;
172         MonoGraphOptions value;
173 } GraphName;
174
175 static const GraphName 
176 graph_names [] = {
177         {"cfg",      "Control Flow Graph (CFG)" ,               MONO_GRAPH_CFG},
178         {"dtree",    "Dominator Tree",                          MONO_GRAPH_DTREE},
179         {"code",     "CFG showing code",                        MONO_GRAPH_CFG_CODE},
180         {"ssa",      "CFG showing code after SSA translation",  MONO_GRAPH_CFG_SSA},
181         {"optcode",  "CFG showing code after IR optimizations", MONO_GRAPH_CFG_OPTCODE}
182 };
183
184 static MonoGraphOptions
185 mono_parse_graph_options (const char* p)
186 {
187         const char *n;
188         int i, len;
189
190         for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
191                 n = graph_names [i].name;
192                 len = strlen (n);
193                 if (strncmp (p, n, len) == 0)
194                         return graph_names [i].value;
195         }
196
197         fprintf (stderr, "Invalid graph name provided: %s\n", p);
198         exit (1);
199 }
200
201 int
202 mono_parse_default_optimizations (const char* p)
203 {
204         guint32 opt;
205
206         opt = parse_optimizations (p);
207         return opt;
208 }
209
210 static char*
211 opt_descr (guint32 flags) {
212         GString *str = g_string_new ("");
213         int i, need_comma;
214
215         need_comma = 0;
216         for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
217                 if (flags & (1 << i)) {
218                         if (need_comma)
219                                 g_string_append_c (str, ',');
220                         g_string_append (str, opt_names [i].name);
221                         need_comma = 1;
222                 }
223         }
224         return g_string_free (str, FALSE);
225 }
226
227 static const guint32
228 opt_sets [] = {
229        0,
230        MONO_OPT_PEEPHOLE,
231        MONO_OPT_BRANCH,
232        MONO_OPT_CFOLD,
233        MONO_OPT_FCMOV,
234        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS,
235        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS,
236        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP,
237        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_CFOLD,
238        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE,
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,
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_SSA,
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,
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,
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_EXCEPTION | MONO_OPT_ABCREM | MONO_OPT_SSAPRE,
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_ABCREM,
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_SSAPRE,
246        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
247 };
248
249 typedef int (*TestMethod) (void);
250
251 #if 0
252 static void
253 domain_dump_native_code (MonoDomain *domain) {
254         // need to poke into the domain, move to metadata/domain.c
255         // need to empty jit_info_table and code_mp
256 }
257 #endif
258
259 static int
260 mini_regression (MonoImage *image, int verbose, int *total_run) {
261         guint32 i, opt, opt_flags;
262         MonoMethod *method;
263         MonoCompile *cfg;
264         char *n;
265         int result, expected, failed, cfailed, run, code_size, total;
266         TestMethod func;
267         GTimer *timer = g_timer_new ();
268
269         if (mini_stats_fd) {
270                 fprintf (mini_stats_fd, "$stattitle = \'Mono Benchmark Results (various optimizations)\';\n");
271
272                 fprintf (mini_stats_fd, "$graph->set_legend(qw(");
273                 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); opt++) {
274                         opt_flags = opt_sets [opt];
275                         n = opt_descr (opt_flags);
276                         if (!n [0])
277                                 n = (char *)"none";
278                         if (opt)
279                                 fprintf (mini_stats_fd, " ");
280                         fprintf (mini_stats_fd, "%s", n);
281                 
282
283                 }
284                 fprintf (mini_stats_fd, "));\n");
285
286                 fprintf (mini_stats_fd, "@data = (\n");
287                 fprintf (mini_stats_fd, "[");
288         }
289
290         /* load the metadata */
291         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
292                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
293                 mono_class_init (method->klass);
294
295                 if (!strncmp (method->name, "test_", 5) && mini_stats_fd) {
296                         fprintf (mini_stats_fd, "\"%s\",", method->name);
297                 }
298         }
299         if (mini_stats_fd)
300                 fprintf (mini_stats_fd, "],\n");
301
302
303         total = 0;
304         *total_run = 0;
305         for (opt = 0; opt < G_N_ELEMENTS (opt_sets); ++opt) {
306                 double elapsed, comp_time, start_time;
307                 MonoJitInfo *jinfo;
308
309                 opt_flags = opt_sets [opt];
310                 mono_set_defaults (verbose, opt_flags);
311                 n = opt_descr (opt_flags);
312                 g_print ("Test run: image=%s, opts=%s\n", mono_image_get_filename (image), n);
313                 g_free (n);
314                 cfailed = failed = run = code_size = 0;
315                 comp_time = elapsed = 0.0;
316
317                 /* fixme: ugly hack - delete all previously compiled methods */
318                 g_hash_table_destroy (mono_domain_get ()->jit_trampoline_hash);
319                 mono_domain_get ()->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
320                 g_hash_table_destroy (mono_domain_get ()->jit_code_hash);
321                 mono_domain_get ()->jit_code_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
322
323                 g_timer_start (timer);
324                 if (mini_stats_fd)
325                         fprintf (mini_stats_fd, "[");
326                 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
327                         method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
328                         if (strncmp (method->name, "test_", 5) == 0) {
329                                 expected = atoi (method->name + 5);
330                                 run++;
331                                 start_time = g_timer_elapsed (timer, NULL);
332                                 comp_time -= start_time; 
333                                 cfg = mini_method_compile (method, opt_flags, mono_get_root_domain (), TRUE, FALSE, 0);
334                                 comp_time += g_timer_elapsed (timer, NULL);
335                                 if (cfg) {
336                                         if (verbose >= 2)
337                                                 g_print ("Running '%s' ...\n", method->name);
338 #ifdef MONO_USE_AOT_COMPILER
339                                         if ((jinfo = mono_aot_get_method (mono_get_root_domain (), method)))
340                                                 func = jinfo->code_start;
341                                         else
342 #endif
343                                                 func = (TestMethod)(gpointer)cfg->native_code;
344                                         func = (TestMethod)mono_create_ftnptr (mono_get_root_domain (), func);
345                                         result = func ();
346                                         if (result != expected) {
347                                                 failed++;
348                                                 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
349                                         }
350                                         code_size += cfg->code_len;
351                                         mono_destroy_compile (cfg);
352
353                                 } else {
354                                         cfailed++;
355                                         if (verbose)
356                                                 g_print ("Test '%s' failed compilation.\n", method->name);
357                                 }
358                                 if (mini_stats_fd)
359                                         fprintf (mini_stats_fd, "%f, ", 
360                                                  g_timer_elapsed (timer, NULL) - start_time);
361                         }
362                 }
363                 if (mini_stats_fd)
364                         fprintf (mini_stats_fd, "],\n");
365                 g_timer_stop (timer);
366                 elapsed = g_timer_elapsed (timer, NULL);
367                 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n", 
368                         run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
369                 g_print ("Elapsed time: %f secs (%f, %f), Code size: %d\n\n", elapsed, 
370                          elapsed - comp_time, comp_time, code_size);
371                 total += failed + cfailed;
372                 *total_run += run;
373         }
374
375         if (mini_stats_fd) {
376                 fprintf (mini_stats_fd, ");\n");
377                 fflush (mini_stats_fd);
378         }
379
380         g_timer_destroy (timer);
381         return total;
382 }
383
384 static int
385 mini_regression_list (int verbose, int count, char *images [])
386 {
387         int i, total, total_run, run;
388         MonoAssembly *ass;
389         
390         total_run =  total = 0;
391         for (i = 0; i < count; ++i) {
392                 ass = mono_assembly_open (images [i], NULL);
393                 if (!ass) {
394                         g_warning ("failed to load assembly: %s", images [i]);
395                         continue;
396                 }
397                 total += mini_regression (mono_assembly_get_image (ass), verbose, &run);
398                 total_run += run;
399         }
400         g_print ("Overall results: tests: %d, failed: %d, opt combinations: %d (pass: %.2f%%)\n", 
401                 total_run, total, (int)G_N_ELEMENTS (opt_sets), 100.0*(total_run-total)/total_run);
402         return total;
403 }
404
405 enum {
406         DO_BENCH,
407         DO_REGRESSION,
408         DO_COMPILE,
409         DO_EXEC,
410         DO_DRAW
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 {
819                         fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
820                         return 1;
821                 }
822         }
823
824         if (!argv [i]) {
825                 mini_usage ();
826                 return 1;
827         }
828
829         if (mono_compile_aot || action == DO_EXEC) {
830                 g_set_prgname (argv[i]);
831         }
832
833         if (enable_profile) {
834                 /* Needed because of TLS accesses in mono_profiler_load () */
835                 MONO_GC_PRE_INIT ();
836                 mono_profiler_load (profile_options);
837         }
838
839         if (trace_options != NULL){
840                 /* 
841                  * Need to call this before mini_init () so we can trace methods 
842                  * compiled there too.
843                  */
844                 mono_jit_trace_calls = mono_trace_parse_options (trace_options);
845                 if (mono_jit_trace_calls == NULL)
846                         exit (1);
847         }
848
849         mono_set_defaults (mini_verbose, opt);
850         domain = mini_init (argv [i]);
851         
852         switch (action) {
853         case DO_REGRESSION:
854                 if (mini_regression_list (mini_verbose, argc -i, argv + i)) {
855                         g_print ("Regression ERRORS!\n");
856                         mini_cleanup (domain);
857                         return 1;
858                 }
859                 mini_cleanup (domain);
860                 return 0;
861         case DO_BENCH:
862                 if (argc - i != 1 || mname == NULL) {
863                         g_print ("Usage: mini --ncompile num --compile method assembly\n");
864                         mini_cleanup (domain);
865                         return 1;
866                 }
867                 aname = argv [i];
868                 break;
869         case DO_COMPILE:
870                 if (argc - i != 1) {
871                         mini_usage ();
872                         mini_cleanup (domain);
873                         return 1;
874                 }
875                 aname = argv [i];
876                 break;
877         case DO_DRAW:
878                 if (argc - i != 1 || mname == NULL) {
879                         mini_usage ();
880                         mini_cleanup (domain);
881                         return 1;
882                 }
883                 aname = argv [i];
884                 break;
885         default:
886                 if (argc - i < 1) {
887                         mini_usage ();
888                         mini_cleanup (domain);
889                         return 1;
890                 }
891                 aname = argv [i];
892                 break;
893         }
894
895         if (enable_debugging) {
896                 mono_debug_init (MONO_DEBUG_FORMAT_MONO);
897                 mono_debug_init_1 (domain);
898         }
899
900         /* Parse gac loading options before loading assemblies. */
901         if (mono_compile_aot || action == DO_EXEC) {
902                 mono_config_parse (config_file);
903         }
904
905         assembly = mono_assembly_open (aname, NULL);
906         if (!assembly) {
907                 fprintf (stderr, "cannot open assembly %s\n", aname);
908                 mini_cleanup (domain);
909                 return 2;
910         }
911
912         if (trace_options != NULL)
913                 mono_trace_set_assembly (assembly);
914
915         if (enable_debugging)
916                 mono_debug_init_2 (assembly);
917
918         if (mono_compile_aot || action == DO_EXEC) {
919                 const char *error;
920
921                 //mono_set_rootdir ();
922
923                 error = mono_check_corlib_version ();
924                 if (error) {
925                         fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
926                         fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.go-mono.com/daily.\n");
927                         exit (1);
928                 }
929
930 #ifdef PLATFORM_WIN32
931                 /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
932                 if (!mono_compile_aot && ((MonoCLIImageInfo*)(mono_assembly_get_image (assembly)->image_info))->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
933                         FreeConsole ();
934 #endif
935
936                 main_args.domain = domain;
937                 main_args.file = aname;         
938                 main_args.argc = argc - i;
939                 main_args.argv = argv + i;
940                 main_args.opts = opt;
941                 main_args.aot_options = aot_options;
942 #if RUN_IN_SUBTHREAD
943                 mono_runtime_exec_managed_code (domain, main_thread_handler, &main_args);
944 #else
945                 main_thread_handler (&main_args);
946                 mono_thread_manage ();
947 #endif
948                 mini_cleanup (domain);
949
950                 /* Look up return value from System.Environment.ExitCode */
951                 i = mono_environment_exitcode_get ();
952                 return i;
953         } else if (action == DO_COMPILE) {
954                 compile_all_methods (assembly, mini_verbose, opt);
955                 mini_cleanup (domain);
956                 return 0;
957         }
958         desc = mono_method_desc_new (mname, 0);
959         if (!desc) {
960                 g_print ("Invalid method name %s\n", mname);
961                 mini_cleanup (domain);
962                 return 3;
963         }
964         method = mono_method_desc_search_in_image (desc, mono_assembly_get_image (assembly));
965         if (!method) {
966                 g_print ("Cannot find method %s\n", mname);
967                 mini_cleanup (domain);
968                 return 3;
969         }
970
971         if (action == DO_DRAW) {
972                 int part = 0;
973
974                 switch (mono_graph_options) {
975                 case MONO_GRAPH_DTREE:
976                         part = 1;
977                         opt |= MONO_OPT_LOOP;
978                         break;
979                 case MONO_GRAPH_CFG_CODE:
980                         part = 1;
981                         break;
982                 case MONO_GRAPH_CFG_SSA:
983                         part = 2;
984                         break;
985                 case MONO_GRAPH_CFG_OPTCODE:
986                         part = 3;
987                         break;
988                 default:
989                         break;
990                 }
991
992                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
993                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
994                         MonoMethod *nm;
995                         nm = mono_marshal_get_native_wrapper (method);
996                         cfg = mini_method_compile (nm, opt, mono_get_root_domain (), FALSE, FALSE, part);
997                 }
998                 else
999                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, part);
1000                 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
1001                         g_warning ("no SSA info available (use -O=deadce)");
1002                         return 1;
1003                 }
1004                 mono_draw_graph (cfg, mono_graph_options);
1005                 mono_destroy_compile (cfg);
1006
1007         } else if (action == DO_BENCH) {
1008                 if (mini_stats_fd) {
1009                         const char *n;
1010                         double no_opt_time = 0.0;
1011                         GTimer *timer = g_timer_new ();
1012                         fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n", 
1013                                  mono_method_full_name (method, TRUE));
1014                         fprintf (mini_stats_fd, "@data = (\n");
1015                         fprintf (mini_stats_fd, "[");
1016                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
1017                                 opt = opt_sets [i];
1018                                 n = opt_descr (opt);
1019                                 if (!n [0])
1020                                         n = "none";
1021                                 fprintf (mini_stats_fd, "\"%s\",", n);
1022                         }
1023                         fprintf (mini_stats_fd, "],\n[");
1024
1025                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
1026                                 int j;
1027                                 double elapsed;
1028                                 opt = opt_sets [i];
1029                                 g_timer_start (timer);
1030                                 for (j = 0; j < count; ++j) {
1031                                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1032                                         mono_destroy_compile (cfg);
1033                                 }
1034                                 g_timer_stop (timer);
1035                                 elapsed = g_timer_elapsed (timer, NULL);
1036                                 if (!opt)
1037                                         no_opt_time = elapsed;
1038                                 fprintf (mini_stats_fd, "%f, ", elapsed);
1039                         }
1040                         fprintf (mini_stats_fd, "]");
1041                         if (no_opt_time > 0.0) {
1042                                 fprintf (mini_stats_fd, ", \n[");
1043                                 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) 
1044                                         fprintf (mini_stats_fd, "%f,", no_opt_time);
1045                                 fprintf (mini_stats_fd, "]");
1046                         }
1047                         fprintf (mini_stats_fd, ");\n");
1048                 } else {
1049                         for (i = 0; i < count; ++i) {
1050                                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1051                                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
1052                                         method = mono_marshal_get_native_wrapper (method);
1053
1054                                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1055                                 mono_destroy_compile (cfg);
1056                         }
1057                 }
1058         } else {
1059                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1060                 mono_destroy_compile (cfg);
1061         }
1062
1063         mini_cleanup (domain);
1064         return 0;
1065 }
1066
1067 MonoDomain * 
1068 mono_jit_init (const char *file)
1069 {
1070         return mini_init (file);
1071 }
1072
1073 void        
1074 mono_jit_cleanup (MonoDomain *domain)
1075 {
1076         mini_cleanup (domain);
1077 }