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