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