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