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