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