2008-05-21T0620 C.J. Adams-collier <cjac@colliertech.org>
[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 #if HAVE_SCHED_SETAFFINITY
15 #include <sched.h>
16 #endif
17 #ifdef HAVE_UNISTD_H
18 #include <unistd.h>
19 #endif
20
21 #include <mono/metadata/assembly.h>
22 #include <mono/metadata/loader.h>
23 #include <mono/metadata/tabledefs.h>
24 #include <mono/metadata/class.h>
25 #include <mono/metadata/object.h>
26 #include <mono/metadata/exception.h>
27 #include <mono/metadata/opcodes.h>
28 #include <mono/metadata/mono-endian.h>
29 #include <mono/metadata/tokentype.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/threads.h>
32 #include <mono/metadata/marshal.h>
33 #include <mono/metadata/socket-io.h>
34 #include <mono/metadata/appdomain.h>
35 #include <mono/metadata/debug-helpers.h>
36 #include <mono/io-layer/io-layer.h>
37 #include "mono/metadata/profiler.h"
38 #include <mono/metadata/profiler-private.h>
39 #include <mono/metadata/mono-config.h>
40 #include <mono/metadata/environment.h>
41 #include <mono/metadata/verify.h>
42 #include <mono/metadata/verify-internals.h>
43 #include <mono/metadata/mono-debug.h>
44 #include <mono/metadata/security-manager.h>
45 #include <mono/metadata/security-core-clr.h>
46 #include <mono/metadata/gc-internal.h>
47 #include <mono/metadata/coree.h>
48 #include "mono/utils/mono-counters.h"
49 #include <mono/os/gc_wrapper.h>
50
51 #include "mini.h"
52 #include "jit.h"
53 #include <string.h>
54 #include <ctype.h>
55 #include "inssel.h"
56 #include <locale.h>
57 #include "version.h"
58
59 static FILE *mini_stats_fd = NULL;
60
61 static void mini_usage (void);
62
63 #ifdef PLATFORM_WIN32
64 /* Need this to determine whether to detach console */
65 #include <mono/metadata/cil-coff.h>
66 /* This turns off command line globbing under win32 */
67 int _CRT_glob = 0;
68 #endif
69
70 typedef void (*OptFunc) (const char *p);
71
72 #undef OPTFLAG
73 #ifdef HAVE_ARRAY_ELEM_INIT
74 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
75 #define MSGSTRFIELD1(line) str##line
76
77 static const struct msgstr_t {
78 #define OPTFLAG(id,shift,name,desc) char MSGSTRFIELD(__LINE__) [sizeof (name) + sizeof (desc)];
79 #include "optflags-def.h"
80 #undef OPTFLAG
81 } opstr = {
82 #define OPTFLAG(id,shift,name,desc) name "\0" desc,
83 #include "optflags-def.h"
84 #undef OPTFLAG
85 };
86 static const gint16 opt_names [] = {
87 #define OPTFLAG(id,shift,name,desc) [(shift)] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
88 #include "optflags-def.h"
89 #undef OPTFLAG
90 };
91
92 #define optflag_get_name(id) ((const char*)&opstr + opt_names [(id)])
93 #define optflag_get_desc(id) (optflag_get_name(id) + 1 + strlen (optflag_get_name(id)))
94
95 #else /* !HAVE_ARRAY_ELEM_INIT */
96 typedef struct {
97         const char* name;
98         const char* desc;
99 } OptName;
100
101 #define OPTFLAG(id,shift,name,desc) {name,desc},
102 static const OptName 
103 opt_names [] = {
104 #include "optflags-def.h"
105         {NULL, NULL}
106 };
107 #define optflag_get_name(id) (opt_names [(id)].name)
108 #define optflag_get_desc(id) (opt_names [(id)].desc)
109
110 #endif
111
112 static const OptFunc
113 opt_funcs [sizeof (int) * 8] = {
114         NULL
115 };
116
117 #define DEFAULT_OPTIMIZATIONS ( \
118         MONO_OPT_PEEPHOLE |     \
119         MONO_OPT_CFOLD |        \
120         MONO_OPT_INLINE |       \
121         MONO_OPT_CONSPROP |     \
122         MONO_OPT_COPYPROP |     \
123         MONO_OPT_TREEPROP |     \
124         MONO_OPT_DEADCE |       \
125         MONO_OPT_BRANCH |       \
126         MONO_OPT_LINEARS |      \
127         MONO_OPT_INTRINS |  \
128         MONO_OPT_LOOP |  \
129         MONO_OPT_EXCEPTION |  \
130         MONO_OPT_AOT)
131
132 #define EXCLUDED_FROM_ALL (MONO_OPT_SHARED | MONO_OPT_PRECOMP)
133
134 static guint32
135 parse_optimizations (const char* p)
136 {
137         /* the default value */
138         guint32 opt = DEFAULT_OPTIMIZATIONS;
139         guint32 exclude = 0;
140         const char *n;
141         int i, invert, len;
142
143         /* call out to cpu detection code here that sets the defaults ... */
144         opt |= mono_arch_cpu_optimizazions (&exclude);
145         opt &= ~exclude;
146         if (!p)
147                 return opt;
148
149         while (*p) {
150                 if (*p == '-') {
151                         p++;
152                         invert = TRUE;
153                 } else {
154                         invert = FALSE;
155                 }
156                 for (i = 0; i < G_N_ELEMENTS (opt_names) && optflag_get_name (i); ++i) {
157                         n = optflag_get_name (i);
158                         len = strlen (n);
159                         if (strncmp (p, n, len) == 0) {
160                                 if (invert)
161                                         opt &= ~ (1 << i);
162                                 else
163                                         opt |= 1 << i;
164                                 p += len;
165                                 if (*p == ',') {
166                                         p++;
167                                         break;
168                                 } else if (*p == '=') {
169                                         p++;
170                                         if (opt_funcs [i])
171                                                 opt_funcs [i] (p);
172                                         while (*p && *p++ != ',');
173                                         break;
174                                 }
175                                 /* error out */
176                                 break;
177                         }
178                 }
179                 if (i == G_N_ELEMENTS (opt_names) || !optflag_get_name (i)) {
180                         if (strncmp (p, "all", 3) == 0) {
181                                 if (invert)
182                                         opt = 0;
183                                 else
184                                         opt = ~(EXCLUDED_FROM_ALL | exclude);
185                                 p += 3;
186                                 if (*p == ',')
187                                         p++;
188                         } else {
189                                 fprintf (stderr, "Invalid optimization name `%s'\n", p);
190                                 exit (1);
191                         }
192                 }
193         }
194         return opt;
195 }
196
197 static gboolean
198 parse_debug_options (const char* p)
199 {
200         MonoDebugOptions *opt = mini_get_debug_options ();
201
202         do {
203                 if (!*p) {
204                         fprintf (stderr, "Syntax error; expected debug option name\n");
205                         return FALSE;
206                 }
207
208                 if (!strncmp (p, "casts", 5)) {
209                         opt->better_cast_details = TRUE;
210                         p += 5;
211                 } else if (!strncmp (p, "mdb-optimizations", 17)) {
212                         opt->mdb_optimizations = TRUE;
213                         p += 17;
214                 } else {
215                         fprintf (stderr, "Invalid debug option `%s', use --help-debug for details\n", p);
216                         return FALSE;
217                 }
218
219                 if (*p == ',') {
220                         p++;
221                         if (!*p) {
222                                 fprintf (stderr, "Syntax error; expected debug option name\n");
223                                 return FALSE;
224                         }
225                 }
226         } while (*p);
227
228         return TRUE;
229 }
230
231 typedef struct {
232         const char name [6];
233         const char desc [18];
234         MonoGraphOptions value;
235 } GraphName;
236
237 static const GraphName 
238 graph_names [] = {
239         {"cfg",      "Control Flow",                            MONO_GRAPH_CFG},
240         {"dtree",    "Dominator Tree",                          MONO_GRAPH_DTREE},
241         {"code",     "CFG showing code",                        MONO_GRAPH_CFG_CODE},
242         {"ssa",      "CFG after SSA",                           MONO_GRAPH_CFG_SSA},
243         {"optc",     "CFG after IR opts",                       MONO_GRAPH_CFG_OPTCODE}
244 };
245
246 static MonoGraphOptions
247 mono_parse_graph_options (const char* p)
248 {
249         const char *n;
250         int i, len;
251
252         for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
253                 n = graph_names [i].name;
254                 len = strlen (n);
255                 if (strncmp (p, n, len) == 0)
256                         return graph_names [i].value;
257         }
258
259         fprintf (stderr, "Invalid graph name provided: %s\n", p);
260         exit (1);
261 }
262
263 int
264 mono_parse_default_optimizations (const char* p)
265 {
266         guint32 opt;
267
268         opt = parse_optimizations (p);
269         return opt;
270 }
271
272 static char*
273 opt_descr (guint32 flags) {
274         GString *str = g_string_new ("");
275         int i, need_comma;
276
277         need_comma = 0;
278         for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
279                 if (flags & (1 << i)) {
280                         if (need_comma)
281                                 g_string_append_c (str, ',');
282                         g_string_append (str, optflag_get_name (i));
283                         need_comma = 1;
284                 }
285         }
286         return g_string_free (str, FALSE);
287 }
288
289 static const guint32
290 opt_sets [] = {
291        0,
292        MONO_OPT_PEEPHOLE,
293        MONO_OPT_BRANCH,
294        MONO_OPT_CFOLD,
295        MONO_OPT_FCMOV,
296        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS,
297        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS,
298        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP,
299        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_CFOLD,
300        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE,
301        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,
302        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,
303        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,
304        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,
305        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,
306        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,
307        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,
308        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,
309        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
310 };
311
312 typedef int (*TestMethod) (void);
313
314 #if 0
315 static void
316 domain_dump_native_code (MonoDomain *domain) {
317         // need to poke into the domain, move to metadata/domain.c
318         // need to empty jit_info_table and code_mp
319 }
320 #endif
321
322 static int
323 mini_regression (MonoImage *image, int verbose, int *total_run) {
324         guint32 i, opt, opt_flags;
325         MonoMethod *method;
326         MonoCompile *cfg;
327         char *n;
328         int result, expected, failed, cfailed, run, code_size, total;
329         TestMethod func;
330         GTimer *timer = g_timer_new ();
331
332         if (mini_stats_fd) {
333                 fprintf (mini_stats_fd, "$stattitle = \'Mono Benchmark Results (various optimizations)\';\n");
334
335                 fprintf (mini_stats_fd, "$graph->set_legend(qw(");
336                 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); opt++) {
337                         opt_flags = opt_sets [opt];
338                         n = opt_descr (opt_flags);
339                         if (!n [0])
340                                 n = (char *)"none";
341                         if (opt)
342                                 fprintf (mini_stats_fd, " ");
343                         fprintf (mini_stats_fd, "%s", n);
344                 
345
346                 }
347                 fprintf (mini_stats_fd, "));\n");
348
349                 fprintf (mini_stats_fd, "@data = (\n");
350                 fprintf (mini_stats_fd, "[");
351         }
352
353         /* load the metadata */
354         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
355                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
356                 mono_class_init (method->klass);
357
358                 if (!strncmp (method->name, "test_", 5) && mini_stats_fd) {
359                         fprintf (mini_stats_fd, "\"%s\",", method->name);
360                 }
361         }
362         if (mini_stats_fd)
363                 fprintf (mini_stats_fd, "],\n");
364
365
366         total = 0;
367         *total_run = 0;
368         for (opt = 0; opt < G_N_ELEMENTS (opt_sets); ++opt) {
369                 double elapsed, comp_time, start_time;
370
371                 opt_flags = opt_sets [opt];
372                 mono_set_defaults (verbose, opt_flags);
373                 n = opt_descr (opt_flags);
374                 g_print ("Test run: image=%s, opts=%s\n", mono_image_get_filename (image), n);
375                 g_free (n);
376                 cfailed = failed = run = code_size = 0;
377                 comp_time = elapsed = 0.0;
378
379                 /* fixme: ugly hack - delete all previously compiled methods */
380                 g_hash_table_destroy (mono_domain_get ()->jit_trampoline_hash);
381                 mono_domain_get ()->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
382                 mono_internal_hash_table_destroy (&(mono_domain_get ()->jit_code_hash));
383                 mono_jit_code_hash_init (&(mono_domain_get ()->jit_code_hash));
384
385                 g_timer_start (timer);
386                 if (mini_stats_fd)
387                         fprintf (mini_stats_fd, "[");
388                 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
389                         method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
390                         if (strncmp (method->name, "test_", 5) == 0) {
391                                 expected = atoi (method->name + 5);
392                                 run++;
393                                 start_time = g_timer_elapsed (timer, NULL);
394                                 comp_time -= start_time; 
395                                 cfg = mini_method_compile (method, opt_flags, mono_get_root_domain (), TRUE, FALSE, 0);
396                                 comp_time += g_timer_elapsed (timer, NULL);
397                                 if (cfg->exception_type == MONO_EXCEPTION_NONE) {
398                                         if (verbose >= 2)
399                                                 g_print ("Running '%s' ...\n", method->name);
400 #ifdef MONO_USE_AOT_COMPILER
401                                         if ((func = mono_aot_get_method (mono_get_root_domain (), method)))
402                                                 ;
403                                         else
404 #endif
405                                                 func = (TestMethod)(gpointer)cfg->native_code;
406                                         func = (TestMethod)mono_create_ftnptr (mono_get_root_domain (), func);
407                                         result = func ();
408                                         if (result != expected) {
409                                                 failed++;
410                                                 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
411                                         }
412                                         code_size += cfg->code_len;
413                                         mono_destroy_compile (cfg);
414
415                                 } else {
416                                         cfailed++;
417                                         if (verbose)
418                                                 g_print ("Test '%s' failed compilation.\n", method->name);
419                                 }
420                                 if (mini_stats_fd)
421                                         fprintf (mini_stats_fd, "%f, ", 
422                                                  g_timer_elapsed (timer, NULL) - start_time);
423                         }
424                 }
425                 if (mini_stats_fd)
426                         fprintf (mini_stats_fd, "],\n");
427                 g_timer_stop (timer);
428                 elapsed = g_timer_elapsed (timer, NULL);
429                 if (failed > 0 || cfailed > 0){
430                         g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n", 
431                                  run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
432                 } else {
433                         g_print ("Results: total tests: %d, all pass \n",  run);
434                 }
435                 
436                 g_print ("Elapsed time: %f secs (%f, %f), Code size: %d\n\n", elapsed, 
437                          elapsed - comp_time, comp_time, code_size);
438                 total += failed + cfailed;
439                 *total_run += run;
440         }
441
442         if (mini_stats_fd) {
443                 fprintf (mini_stats_fd, ");\n");
444                 fflush (mini_stats_fd);
445         }
446
447         g_timer_destroy (timer);
448         return total;
449 }
450
451 static int
452 mini_regression_list (int verbose, int count, char *images [])
453 {
454         int i, total, total_run, run;
455         MonoAssembly *ass;
456         
457         total_run =  total = 0;
458         for (i = 0; i < count; ++i) {
459                 ass = mono_assembly_open (images [i], NULL);
460                 if (!ass) {
461                         g_warning ("failed to load assembly: %s", images [i]);
462                         continue;
463                 }
464                 total += mini_regression (mono_assembly_get_image (ass), verbose, &run);
465                 total_run += run;
466         }
467         if (total > 0){
468                 g_print ("Overall results: tests: %d, failed: %d, opt combinations: %d (pass: %.2f%%)\n", 
469                          total_run, total, (int)G_N_ELEMENTS (opt_sets), 100.0*(total_run-total)/total_run);
470         } else {
471                 g_print ("Overall results: tests: %d, 100%% pass, opt combinations: %d\n", 
472                          total_run, (int)G_N_ELEMENTS (opt_sets));
473         }
474         
475         return total;
476 }
477
478 #ifdef MONO_JIT_INFO_TABLE_TEST
479 typedef struct _JitInfoData
480 {
481         guint start;
482         guint length;
483         MonoJitInfo *ji;
484         struct _JitInfoData *next;
485 } JitInfoData;
486
487 typedef struct
488 {
489         guint start;
490         guint length;
491         int num_datas;
492         JitInfoData *data;
493 } Region;
494
495 typedef struct
496 {
497         int num_datas;
498         int num_regions;
499         Region *regions;
500         int num_frees;
501         JitInfoData *frees;
502 } ThreadData;
503
504 static int num_threads;
505 static ThreadData *thread_datas;
506 static MonoDomain *test_domain;
507
508 static JitInfoData*
509 alloc_random_data (Region *region)
510 {
511         JitInfoData **data;
512         JitInfoData *prev;
513         guint prev_end;
514         guint next_start;
515         guint max_len;
516         JitInfoData *d;
517         int num_retries = 0;
518         int pos, i;
519
520  restart:
521         prev = NULL;
522         data = &region->data;
523         pos = random () % (region->num_datas + 1);
524         i = 0;
525         while (*data != NULL) {
526                 if (i++ == pos)
527                         break;
528                 prev = *data;
529                 data = &(*data)->next;
530         }
531
532         if (prev == NULL)
533                 g_assert (*data == region->data);
534         else
535                 g_assert (prev->next == *data);
536
537         if (prev == NULL)
538                 prev_end = region->start;
539         else
540                 prev_end = prev->start + prev->length;
541
542         if (*data == NULL)
543                 next_start = region->start + region->length;
544         else
545                 next_start = (*data)->start;
546
547         g_assert (prev_end <= next_start);
548
549         max_len = next_start - prev_end;
550         if (max_len < 128) {
551                 if (++num_retries >= 10)
552                         return NULL;
553                 goto restart;
554         }
555         if (max_len > 1024)
556                 max_len = 1024;
557
558         d = g_new0 (JitInfoData, 1);
559         d->start = prev_end + random () % (max_len / 2);
560         d->length = random () % MIN (max_len, next_start - d->start) + 1;
561
562         g_assert (d->start >= prev_end && d->start + d->length <= next_start);
563
564         d->ji = g_new0 (MonoJitInfo, 1);
565         d->ji->method = (MonoMethod*) 0xABadBabe;
566         d->ji->code_start = (gpointer)(gulong) d->start;
567         d->ji->code_size = d->length;
568         d->ji->cas_inited = 1;  /* marks an allocated jit info */
569
570         d->next = *data;
571         *data = d;
572
573         ++region->num_datas;
574
575         return d;
576 }
577
578 static JitInfoData**
579 choose_random_data (Region *region)
580 {
581         int n;
582         int i;
583         JitInfoData **d;
584
585         g_assert (region->num_datas > 0);
586
587         n = random () % region->num_datas;
588
589         for (d = &region->data, i = 0;
590              i < n;
591              d = &(*d)->next, ++i)
592                 ;
593
594         return d;
595 }
596
597 static Region*
598 choose_random_region (ThreadData *td)
599 {
600         return &td->regions [random () % td->num_regions];
601 }
602
603 static ThreadData*
604 choose_random_thread (void)
605 {
606         return &thread_datas [random () % num_threads];
607 }
608
609 static void
610 free_jit_info_data (ThreadData *td, JitInfoData *free)
611 {
612         free->next = td->frees;
613         td->frees = free;
614
615         if (++td->num_frees >= 1000) {
616                 int i;
617
618                 for (i = 0; i < 500; ++i)
619                         free = free->next;
620
621                 while (free->next != NULL) {
622                         JitInfoData *next = free->next->next;
623
624                         g_free (free->next->ji);
625                         g_free (free->next);
626                         free->next = next;
627
628                         --td->num_frees;
629                 }
630         }
631 }
632
633 #define NUM_THREADS             8
634 #define REGIONS_PER_THREAD      10
635 #define REGION_SIZE             0x10000
636
637 #define MAX_ADDR                (REGION_SIZE * REGIONS_PER_THREAD * NUM_THREADS)
638
639 #define MODE_ALLOC      1
640 #define MODE_FREE       2
641
642 static void
643 test_thread_func (ThreadData *td)
644 {
645         int mode = MODE_ALLOC;
646         int i = 0;
647         gulong lookup_successes = 0, lookup_failures = 0;
648         MonoDomain *domain = test_domain;
649         int thread_num = (int)(td - thread_datas);
650         gboolean modify_thread = thread_num < NUM_THREADS / 2; /* only half of the threads modify the table */
651
652         for (;;) {
653                 int alloc;
654                 int lookup = 1;
655
656                 if (td->num_datas == 0) {
657                         lookup = 0;
658                         alloc = 1;
659                 } else if (modify_thread && random () % 1000 < 5) {
660                         lookup = 0;
661                         if (mode == MODE_ALLOC)
662                                 alloc = (random () % 100) < 70;
663                         else if (mode == MODE_FREE)
664                                 alloc = (random () % 100) < 30;
665                 }
666
667                 if (lookup) {
668                         /* modify threads sometimes look up their own jit infos */
669                         if (modify_thread && random () % 10 < 5) {
670                                 Region *region = choose_random_region (td);
671
672                                 if (region->num_datas > 0) {
673                                         JitInfoData **data = choose_random_data (region);
674                                         guint pos = (*data)->start + random () % (*data)->length;
675                                         MonoJitInfo *ji = mono_jit_info_table_find (domain, (char*)(gulong) pos);
676
677                                         g_assert ((*data)->ji == ji);
678                                         g_assert (ji->cas_inited);
679                                 }
680                         } else {
681                                 int pos = random () % MAX_ADDR;
682                                 char *addr = (char*)(gulong) pos;
683                                 MonoJitInfo *ji = mono_jit_info_table_find (domain, addr);
684
685                                 if (ji != NULL) {
686                                         g_assert (addr >= (char*)ji->code_start && addr < (char*)ji->code_start + ji->code_size);
687                                         ++lookup_successes;
688                                 } else
689                                         ++lookup_failures;
690                         }
691                 } else if (alloc) {
692                         JitInfoData *data = alloc_random_data (choose_random_region (td));
693
694                         if (data != NULL) {
695                                 mono_jit_info_table_add (domain, data->ji);
696
697                                 ++td->num_datas;
698                         }
699                 } else {
700                         Region *region = choose_random_region (td);
701
702                         if (region->num_datas > 0) {
703                                 JitInfoData **data = choose_random_data (region);
704                                 JitInfoData *free;
705
706                                 mono_jit_info_table_remove (domain, (*data)->ji);
707
708                                 (*data)->ji->cas_inited = 0; /* marks a free jit info */
709
710                                 free = *data;
711                                 *data = (*data)->next;
712
713                                 free_jit_info_data (td, free);
714
715                                 --region->num_datas;
716                                 --td->num_datas;
717                         }
718                 }
719
720                 if (++i % 100000 == 0) {
721                         int j;
722                         g_print ("num datas %d (%ld - %ld): %d", (int)(td - thread_datas),
723                                  lookup_successes, lookup_failures, td->num_datas);
724                         for (j = 0; j < td->num_regions; ++j)
725                                 g_print ("  %d", td->regions [j].num_datas);
726                         g_print ("\n");
727                 }
728
729                 if (td->num_datas < 100)
730                         mode = MODE_ALLOC;
731                 else if (td->num_datas > 2000)
732                         mode = MODE_FREE;
733         }
734 }
735
736 /*
737 static void
738 small_id_thread_func (gpointer arg)
739 {
740         MonoThread *thread = mono_thread_current ();
741         MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
742
743         g_print ("my small id is %d\n", (int)thread->small_id);
744         mono_hazard_pointer_clear (hp, 1);
745         sleep (3);
746         g_print ("done %d\n", (int)thread->small_id);
747 }
748 */
749
750 static void
751 jit_info_table_test (MonoDomain *domain)
752 {
753         int i;
754
755         g_print ("testing jit_info_table\n");
756
757         num_threads = NUM_THREADS;
758         thread_datas = g_new0 (ThreadData, num_threads);
759
760         for (i = 0; i < num_threads; ++i) {
761                 int j;
762
763                 thread_datas [i].num_regions = REGIONS_PER_THREAD;
764                 thread_datas [i].regions = g_new0 (Region, REGIONS_PER_THREAD);
765
766                 for (j = 0; j < REGIONS_PER_THREAD; ++j) {
767                         thread_datas [i].regions [j].start = (num_threads * j + i) * REGION_SIZE;
768                         thread_datas [i].regions [j].length = REGION_SIZE;
769                 }
770         }
771
772         test_domain = domain;
773
774         /*
775         for (i = 0; i < 72; ++i)
776                 mono_thread_create (domain, small_id_thread_func, NULL);
777
778         sleep (2);
779         */
780
781         for (i = 0; i < num_threads; ++i)
782                 mono_thread_create (domain, test_thread_func, &thread_datas [i]);
783 }
784 #endif
785
786 enum {
787         DO_BENCH,
788         DO_REGRESSION,
789         DO_COMPILE,
790         DO_EXEC,
791         DO_DRAW,
792         DO_DEBUGGER
793 };
794
795 typedef struct CompileAllThreadArgs {
796         MonoAssembly *ass;
797         int verbose;
798         guint32 opts;
799 } CompileAllThreadArgs;
800
801 static void
802 compile_all_methods_thread_main (CompileAllThreadArgs *args)
803 {
804         MonoAssembly *ass = args->ass;
805         int verbose = args->verbose;
806         MonoImage *image = mono_assembly_get_image (ass);
807         MonoMethod *method;
808         MonoCompile *cfg;
809         int i, count = 0, fail_count = 0;
810
811         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
812                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
813                 MonoMethodSignature *sig;
814
815                 if (mono_metadata_has_generic_params (image, token))
816                         continue;
817
818                 method = mono_get_method (image, token, NULL);
819                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
820                     (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
821                     (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
822                     (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
823                         continue;
824
825                 if (method->klass->generic_container)
826                         continue;
827                 sig = mono_method_signature (method);
828                 if (sig->has_type_parameters)
829                         continue;
830
831                 count++;
832                 if (verbose) {
833                         char * desc = mono_method_full_name (method, TRUE);
834                         g_print ("Compiling %d %s\n", count, desc);
835                         g_free (desc);
836                 }
837                 cfg = mini_method_compile (method, args->opts, mono_get_root_domain (), FALSE, FALSE, 0);
838                 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
839                         printf ("Compilation of %s failed with exception '%s':\n", mono_method_full_name (cfg->method, TRUE), cfg->exception_message);
840                         fail_count ++;
841                 }
842                 mono_destroy_compile (cfg);
843         }
844
845         if (fail_count)
846                 exit (1);
847 }
848
849 static void
850 compile_all_methods (MonoAssembly *ass, int verbose, guint32 opts)
851 {
852         CompileAllThreadArgs args;
853
854         args.ass = ass;
855         args.verbose = verbose;
856         args.opts = opts;
857
858         /* 
859          * Need to create a mono thread since compilation might trigger
860          * running of managed code.
861          */
862         mono_thread_create (mono_domain_get (), compile_all_methods_thread_main, &args);
863
864         mono_thread_manage ();
865 }
866
867 /**
868  * mono_jit_exec:
869  * @assembly: reference to an assembly
870  * @argc: argument count
871  * @argv: argument vector
872  *
873  * Start execution of a program.
874  */
875 int 
876 mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
877 {
878         MonoImage *image = mono_assembly_get_image (assembly);
879         MonoMethod *method;
880         guint32 entry = mono_image_get_entry_point (image);
881
882         if (!entry) {
883                 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
884                 /* FIXME: remove this silly requirement. */
885                 mono_environment_exitcode_set (1);
886                 return 1;
887         }
888
889         method = mono_get_method (image, entry, NULL);
890         if (method == NULL){
891                 g_print ("The entry point method could not be loaded\n");
892                 mono_environment_exitcode_set (1);
893                 return 1;
894         }
895         
896         return mono_runtime_run_main (method, argc, argv, NULL);
897 }
898
899 typedef struct 
900 {
901         MonoDomain *domain;
902         const char *file;
903         int argc;
904         char **argv;
905         guint32 opts;
906         char *aot_options;
907 } MainThreadArgs;
908
909 static void main_thread_handler (gpointer user_data)
910 {
911         MainThreadArgs *main_args = user_data;
912         MonoAssembly *assembly;
913
914         assembly = mono_domain_assembly_open (main_args->domain, main_args->file);
915         if (!assembly){
916                 fprintf (stderr, "Can not open image %s\n", main_args->file);
917                 exit (1);
918         }
919
920         if (mono_compile_aot) {
921                 int res = mono_compile_assembly (assembly, main_args->opts, main_args->aot_options);
922                 printf ("AOT RESULT %d\n", res);
923         } else {
924                 /* 
925                  * This must be done in a thread managed by mono since it can invoke
926                  * managed code.
927                  */
928                 if (main_args->opts & MONO_OPT_PRECOMP)
929                         mono_precompile_assemblies ();
930
931                 mono_jit_exec (main_args->domain, assembly, main_args->argc, main_args->argv);
932         }
933 }
934
935 static void
936 mini_usage_jitdeveloper (void)
937 {
938         int i;
939         
940         fprintf (stdout,
941                  "Runtime and JIT debugging options:\n"
942                  "    --breakonex            Inserts a breakpoint on exceptions\n"
943                  "    --break METHOD         Inserts a breakpoint at METHOD entry\n"
944                  "    --break-at-bb METHOD N Inserts a breakpoint in METHOD at BB N\n"
945                  "    --compile METHOD       Just compile METHOD in assembly\n"
946                  "    --compile-all          Compiles all the methods in the assembly\n"
947                  "    --ncompile N           Number of times to compile METHOD (default: 1)\n"
948                  "    --print-vtable         Print the vtable of all used classes\n"
949                  "    --regression           Runs the regression test contained in the assembly\n"
950                  "    --statfile FILE        Sets the stat file to FILE\n"
951                  "    --stats                Print statistics about the JIT operations\n"
952                  "    --wapi=hps|semdel      IO-layer maintenance\n"
953                  "    --inject-async-exc METHOD OFFSET Inject an asynchronous exception at METHOD\n"
954                  "    --verify-all           Run the verifier on all methods\n"
955                  "\n"
956                  "Other options:\n" 
957                  "    --graph[=TYPE] METHOD  Draws a graph of the specified method:\n");
958         
959         for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
960                 fprintf (stdout, "                           %-10s %s\n", graph_names [i].name, graph_names [i].desc);
961         }
962 }
963
964 static void
965 mini_usage_list_opt (void)
966 {
967         int i;
968         
969         for (i = 0; i < G_N_ELEMENTS (opt_names); ++i)
970                 fprintf (stdout, "                           %-10s %s\n", optflag_get_name (i), optflag_get_desc (i));
971 }
972
973 static void
974 mini_usage (void)
975 {
976         fprintf (stdout,
977                 "Usage is: mono [options] program [program-options]\n"
978                 "\n"
979                 "Development:\n"
980                 "    --aot                  Compiles the assembly to native code\n"
981                 "    --debug[=<options>]    Enable debugging support, use --help-debug for details\n"
982                 "    --profile[=profiler]   Runs in profiling mode with the specified profiler module\n"
983                 "    --trace[=EXPR]         Enable tracing, use --help-trace for details\n"
984                 "    --help-devel           Shows more options available to developers\n"
985                 "\n"
986                 "Runtime:\n"
987                 "    --config FILE          Loads FILE as the Mono config\n"
988                 "    --verbose, -v          Increases the verbosity level\n"
989                 "    --help, -h             Show usage information\n"
990                 "    --version, -V          Show version information\n"
991                 "    --runtime=VERSION      Use the VERSION runtime, instead of autodetecting\n"
992                 "    --optimize=OPT         Turns on or off a specific optimization\n"
993                 "                           Use --list-opt to get a list of optimizations\n"
994                 "    --security[=mode]      Turns on the unsupported security manager (off by default)\n"
995                 "                           mode is one of cas, core-clr, verifiable or validil\n");
996 }
997
998 static void
999 mini_trace_usage (void)
1000 {
1001         fprintf (stdout,
1002                  "Tracing options:\n"
1003                  "   --trace[=EXPR]        Trace every call, optional EXPR controls the scope\n"
1004                  "\n"
1005                  "EXPR is composed of:\n"
1006                  "    all                  All assemblies\n"
1007                  "    none                 No assemblies\n"
1008                  "    program              Entry point assembly\n"
1009                  "    assembly             Specifies an assembly\n"
1010                  "    M:Type:Method        Specifies a method\n"
1011                  "    N:Namespace          Specifies a namespace\n"
1012                  "    T:Type               Specifies a type\n"
1013                  "    +EXPR                Includes expression\n"
1014                  "    -EXPR                Excludes expression\n"
1015                  "    disabled             Don't print any output until toggled via SIGUSR2\n");
1016 }
1017
1018 static void
1019 mini_debug_usage (void)
1020 {
1021         fprintf (stdout,
1022                  "Debugging options:\n"
1023                  "   --debug[=OPTIONS]     Enable debugging support, optional OPTIONS is a comma\n"
1024                  "                         separated list of options\n"
1025                  "\n"
1026                  "OPTIONS is composed of:\n"
1027                  "    casts                Enable more detailed InvalidCastException messages.\n"
1028                  "    mdb-optimizations    Disable some JIT optimizations which are normally\n"
1029                  "                         disabled when running inside the debugger.\n"
1030                  "                         This is useful if you plan to attach to the running\n"
1031                  "                         process with the debugger.\n");
1032 }
1033
1034
1035 static const char info[] =
1036 #ifdef HAVE_KW_THREAD
1037         "\tTLS:           __thread\n"
1038 #else
1039         "\tTLS:           normal\n"
1040 #endif /* HAVE_KW_THREAD */
1041         "\tGC:            " USED_GC_NAME "\n"
1042 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
1043     "\tSIGSEGV:       altstack\n"
1044 #else
1045     "\tSIGSEGV:       normal\n"
1046 #endif
1047 #ifdef HAVE_EPOLL
1048     "\tNotifications: epoll\n"
1049 #else
1050     "\tNotification:  Thread + polling\n"
1051 #endif
1052         "\tArchitecture:  " ARCHITECTURE "\n"
1053         "\tDisabled:      " DISABLED_FEATURES "\n"
1054         "";
1055
1056 #ifndef MONO_ARCH_AOT_SUPPORTED
1057 #define error_if_aot_unsupported() do {fprintf (stderr, "AOT compilation is not supported on this platform.\n"); exit (1);} while (0)
1058 #else
1059 #define error_if_aot_unsupported()
1060 #endif
1061
1062 #ifdef PLATFORM_WIN32
1063 BOOL APIENTRY DllMain (HMODULE module_handle, DWORD reason, LPVOID reserved)
1064 {
1065         if (!GC_DllMain (module_handle, reason, reserved))
1066                 return FALSE;
1067
1068         switch (reason)
1069         {
1070         case DLL_PROCESS_ATTACH:
1071                 mono_module_handle = module_handle;
1072                 mono_install_runtime_load (mini_init);
1073                 break;
1074         case DLL_PROCESS_DETACH:
1075                 if (coree_module_handle)
1076                         FreeLibrary (coree_module_handle);
1077                 break;
1078         }
1079         return TRUE;
1080 }
1081 #endif
1082
1083 int
1084 mono_main (int argc, char* argv[])
1085 {
1086         MainThreadArgs main_args;
1087         MonoAssembly *assembly;
1088         MonoMethodDesc *desc;
1089         MonoMethod *method;
1090         MonoCompile *cfg;
1091         MonoDomain *domain;
1092         MonoImageOpenStatus open_status;
1093         const char* aname, *mname = NULL;
1094         char *config_file = NULL;
1095         int i, count = 1;
1096         int enable_debugging = FALSE;
1097         guint32 opt, action = DO_EXEC;
1098         MonoGraphOptions mono_graph_options = 0;
1099         int mini_verbose = 0;
1100         gboolean enable_profile = FALSE;
1101         char *trace_options = NULL;
1102         char *profile_options = NULL;
1103         char *aot_options = NULL;
1104         char *forced_version = NULL;
1105 #ifdef MONO_JIT_INFO_TABLE_TEST
1106         int test_jit_info_table = FALSE;
1107 #endif
1108
1109         setlocale (LC_ALL, "");
1110
1111 #if HAVE_SCHED_SETAFFINITY
1112         if (getenv ("MONO_NO_SMP")) {
1113                 unsigned long proc_mask = 1;
1114                 sched_setaffinity (getpid(), sizeof (unsigned long), (gpointer)&proc_mask);
1115         }
1116 #endif
1117         if (!g_thread_supported ())
1118                 g_thread_init (NULL);
1119
1120         if (mono_running_on_valgrind () && getenv ("MONO_VALGRIND_LEAK_CHECK")) {
1121                 GMemVTable mem_vtable;
1122
1123                 /* 
1124                  * Instruct glib to use the system allocation functions so valgrind
1125                  * can track the memory allocated by the g_... functions.
1126                  */
1127                 memset (&mem_vtable, 0, sizeof (mem_vtable));
1128                 mem_vtable.malloc = malloc;
1129                 mem_vtable.realloc = realloc;
1130                 mem_vtable.free = free;
1131                 mem_vtable.calloc = calloc;
1132
1133                 g_mem_set_vtable (&mem_vtable);
1134         }
1135
1136         g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
1137         g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
1138
1139         opt = parse_optimizations (NULL);
1140
1141         for (i = 1; i < argc; ++i) {
1142                 if (argv [i] [0] != '-')
1143                         break;
1144                 if (strcmp (argv [i], "--regression") == 0) {
1145                         action = DO_REGRESSION;
1146                 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
1147                         mini_verbose++;
1148                 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
1149                         g_print ("Mono JIT compiler version %s (%s)\nCopyright (C) 2002-2008 Novell, Inc and Contributors. www.mono-project.com\n", VERSION, FULL_VERSION);
1150                         g_print (info);
1151                         if (mini_verbose) {
1152                                 const char *cerror;
1153                                 const char *clibpath;
1154                                 mono_init ("mono");
1155                                 cerror = mono_check_corlib_version ();
1156                                 clibpath = mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown";
1157                                 if (cerror) {
1158                                         g_print ("The currently installed mscorlib doesn't match this runtime version.\n");
1159                                         g_print ("The error is: %s\n", cerror);
1160                                         g_print ("mscorlib.dll loaded at: %s\n", clibpath);
1161                                         return 1;
1162                                 }
1163                         }
1164                         return 0;
1165                 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
1166                         mini_usage ();
1167                         return 0;
1168                 } else if (strcmp (argv [i], "--help-trace") == 0){
1169                         mini_trace_usage ();
1170                         return 0;
1171                 } else if (strcmp (argv [i], "--help-devel") == 0){
1172                         mini_usage_jitdeveloper ();
1173                         return 0;
1174                 } else if (strcmp (argv [i], "--help-debug") == 0){
1175                         mini_debug_usage ();
1176                         return 0;
1177                 } else if (strcmp (argv [i], "--list-opt") == 0){
1178                         mini_usage_list_opt ();
1179                         return 0;
1180                 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
1181                         if (i + 1 >= argc){
1182                                 fprintf (stderr, "error: --statfile requires a filename argument\n");
1183                                 return 1;
1184                         }
1185                         mini_stats_fd = fopen (argv [++i], "w+");
1186                 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
1187                         opt = parse_optimizations (argv [i] + 11);
1188                 } else if (strncmp (argv [i], "-O=", 3) == 0) {
1189                         opt = parse_optimizations (argv [i] + 3);
1190                 } else if (strcmp (argv [i], "--config") == 0) {
1191                         if (i +1 >= argc){
1192                                 fprintf (stderr, "error: --config requires a filename argument\n");
1193                                 return 1;
1194                         }
1195                         config_file = argv [++i];
1196                 } else if (strcmp (argv [i], "--ncompile") == 0) {
1197                         if (i + 1 >= argc){
1198                                 fprintf (stderr, "error: --ncompile requires an argument\n");
1199                                 return 1;
1200                         }
1201                         count = atoi (argv [++i]);
1202                         action = DO_BENCH;
1203                 } else if (strcmp (argv [i], "--trace") == 0) {
1204                         trace_options = (char*)"";
1205                 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
1206                         trace_options = &argv [i][8];
1207                 } else if (strcmp (argv [i], "--breakonex") == 0) {
1208                         mono_break_on_exc = TRUE;
1209                 } else if (strcmp (argv [i], "--break") == 0) {
1210                         if (i+1 >= argc){
1211                                 fprintf (stderr, "Missing method name in --break command line option\n");
1212                                 return 1;
1213                         }
1214                         
1215                         if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
1216                                 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
1217                 } else if (strcmp (argv [i], "--break-at-bb") == 0) {
1218                         if (i + 2 >= argc) {
1219                                 fprintf (stderr, "Missing method name or bb num in --break-at-bb command line option.");
1220                                 return 1;
1221                         }
1222                         mono_break_at_bb_method = mono_method_desc_new (argv [++i], TRUE);
1223                         if (mono_break_at_bb_method == NULL) {
1224                                 fprintf (stderr, "Method name is in a bad format in --break-at-bb command line option.");
1225                                 return 1;
1226                         }
1227                         mono_break_at_bb_bb_num = atoi (argv [++i]);
1228                 } else if (strcmp (argv [i], "--inject-async-exc") == 0) {
1229                         if (i + 2 >= argc) {
1230                                 fprintf (stderr, "Missing method name or position in --inject-async-exc command line option\n");
1231                                 return 1;
1232                         }
1233                         mono_inject_async_exc_method = mono_method_desc_new (argv [++i], TRUE);
1234                         if (mono_inject_async_exc_method == NULL) {
1235                                 fprintf (stderr, "Method name is in a bad format in --inject-async-exc command line option\n");
1236                                 return 1;
1237                         }
1238                         mono_inject_async_exc_pos = atoi (argv [++i]);
1239                 } else if (strcmp (argv [i], "--verify-all") == 0) {
1240                         mono_verifier_enable_verify_all ();
1241                 } else if (strcmp (argv [i], "--print-vtable") == 0) {
1242                         mono_print_vtable = TRUE;
1243                 } else if (strcmp (argv [i], "--stats") == 0) {
1244                         mono_counters_enable (-1);
1245                         mono_stats.enabled = TRUE;
1246                         mono_jit_stats.enabled = TRUE;
1247 #ifndef DISABLE_AOT
1248                 } else if (strcmp (argv [i], "--aot") == 0) {
1249                         error_if_aot_unsupported ();
1250                         mono_compile_aot = TRUE;
1251                 } else if (strncmp (argv [i], "--aot=", 6) == 0) {
1252                         error_if_aot_unsupported ();
1253                         mono_compile_aot = TRUE;
1254                         aot_options = &argv [i][6];
1255 #endif
1256                 } else if (strcmp (argv [i], "--compile-all") == 0) {
1257                         action = DO_COMPILE;
1258                 } else if (strncmp (argv [i], "--runtime=", 10) == 0) {
1259                         forced_version = &argv [i][10];
1260                 } else if (strcmp (argv [i], "--profile") == 0) {
1261                         enable_profile = TRUE;
1262                         profile_options = NULL;
1263                 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
1264                         enable_profile = TRUE;
1265                         profile_options = argv [i] + 10;
1266                 } else if (strcmp (argv [i], "--compile") == 0) {
1267                         if (i + 1 >= argc){
1268                                 fprintf (stderr, "error: --compile option requires a method name argument\n");
1269                                 return 1;
1270                         }
1271                         
1272                         mname = argv [++i];
1273                         action = DO_BENCH;
1274                 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
1275                         if (i + 1 >= argc){
1276                                 fprintf (stderr, "error: --graph option requires a method name argument\n");
1277                                 return 1;
1278                         }
1279                         
1280                         mono_graph_options = mono_parse_graph_options (argv [i] + 8);
1281                         mname = argv [++i];
1282                         action = DO_DRAW;
1283                 } else if (strcmp (argv [i], "--graph") == 0) {
1284                         if (i + 1 >= argc){
1285                                 fprintf (stderr, "error: --graph option requires a method name argument\n");
1286                                 return 1;
1287                         }
1288                         
1289                         mname = argv [++i];
1290                         mono_graph_options = MONO_GRAPH_CFG;
1291                         action = DO_DRAW;
1292                 } else if (strcmp (argv [i], "--debug") == 0) {
1293                         enable_debugging = TRUE;
1294                 } else if (strncmp (argv [i], "--debug=", 8) == 0) {
1295                         enable_debugging = TRUE;
1296                         if (!parse_debug_options (argv [i] + 8))
1297                                 return 1;
1298                 } else if (strcmp (argv [i], "--security") == 0) {
1299                         /* fixme enable verifiable code when the verifier works with 2.0
1300                         * mini_verifier_set_mode (MINI_VERIFIER_MODE_VERIFIABLE);
1301                         */
1302                         mono_security_set_mode (MONO_SECURITY_MODE_CAS);
1303                         mono_activate_security_manager ();
1304                 } else if (strncmp (argv [i], "--security=", 11) == 0) {
1305                         if (strcmp (argv [i] + 11, "temporary-smcs-hack") == 0) {
1306                                 mono_security_set_mode (MONO_SECURITY_MODE_SMCS_HACK);
1307                         } else if (strcmp (argv [i] + 11, "core-clr") == 0) {
1308                                 /* fixme enable verifiable code when the verifier works with 2.0
1309                                  * mini_verifier_set_mode (MINI_VERIFIER_MODE_VERIFIABLE);
1310                                  */
1311                                 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
1312                         } else if (strcmp (argv [i] + 11, "core-clr-test") == 0) {
1313                                 /* fixme should we enable verifiable code here?*/
1314                                 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
1315                                 mono_security_core_clr_test = TRUE;
1316                         } else if (strcmp (argv [i] + 11, "cas") == 0){
1317                                 /* fixme enable verifiable code when the verifier works with 2.0
1318                                  * mini_verifier_set_mode (MINI_VERIFIER_MODE_VERIFIABLE);
1319                                  */
1320                                 mono_security_set_mode (MONO_SECURITY_MODE_CAS);
1321                                 mono_activate_security_manager ();
1322                         } else  if (strcmp (argv [i] + 11, "validil") == 0) {
1323                                 mono_verifier_set_mode (MONO_VERIFIER_MODE_VALID);
1324                         } else  if (strcmp (argv [i] + 11, "verifiable") == 0) {
1325                                 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
1326                         } else  {
1327                                 fprintf (stderr, "error: --security= option has invalid argument (cas, core-clr, verifiable or validil)\n");
1328                                 return 1;
1329                         }
1330                 } else if (strcmp (argv [i], "--desktop") == 0) {
1331 #if defined (HAVE_BOEHM_GC)
1332                         GC_dont_expand = 1;
1333 #endif
1334                         /* Put desktop-specific optimizations here */
1335                 } else if (strcmp (argv [i], "--server") == 0){
1336                         /* Put server-specific optimizations here */
1337                 } else if (strcmp (argv [i], "--inside-mdb") == 0) {
1338                         action = DO_DEBUGGER;
1339                 } else if (strncmp (argv [i], "--wapi=", 7) == 0) {
1340                         if (strcmp (argv [i] + 7, "hps") == 0) {
1341                                 return mini_wapi_hps (argc - i, argv + i);
1342                         } else if (strcmp (argv [i] + 7, "semdel") == 0) {
1343                                 return mini_wapi_semdel (argc - i, argv + i);
1344                         } else if (strcmp (argv [i] + 7, "seminfo") == 0) {
1345                                 return mini_wapi_seminfo (argc - i, argv + i);
1346                         } else {
1347                                 fprintf (stderr, "Invalid --wapi suboption: '%s'\n", argv [i]);
1348                                 return 1;
1349                         }
1350 #ifdef MONO_JIT_INFO_TABLE_TEST
1351                 } else if (strcmp (argv [i], "--test-jit-info-table") == 0) {
1352                         test_jit_info_table = TRUE;
1353 #endif
1354                 } else {
1355                         fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
1356                         return 1;
1357                 }
1358         }
1359
1360         if (!argv [i]) {
1361                 mini_usage ();
1362                 return 1;
1363         }
1364
1365         if ((action == DO_EXEC) && mono_debug_using_mono_debugger ())
1366                 action = DO_DEBUGGER;
1367
1368         if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
1369                 g_set_prgname (argv[i]);
1370         }
1371
1372         if (enable_profile) {
1373                 /* Needed because of TLS accesses in mono_profiler_load () */
1374                 mono_gc_base_init ();
1375                 mono_profiler_load (profile_options);
1376         }
1377
1378         if (trace_options != NULL){
1379                 /* 
1380                  * Need to call this before mini_init () so we can trace methods 
1381                  * compiled there too.
1382                  */
1383                 mono_jit_trace_calls = mono_trace_parse_options (trace_options);
1384                 if (mono_jit_trace_calls == NULL)
1385                         exit (1);
1386         }
1387
1388         if (action == DO_DEBUGGER) {
1389                 enable_debugging = TRUE;
1390
1391 #ifdef MONO_DEBUGGER_SUPPORTED
1392                 mono_debug_init (MONO_DEBUG_FORMAT_DEBUGGER);
1393                 mono_debugger_init ();
1394 #else
1395                 g_print ("The Mono Debugger is not supported on this platform.\n");
1396                 return 1;
1397 #endif
1398         } else if (enable_debugging)
1399                 mono_debug_init (MONO_DEBUG_FORMAT_MONO);
1400
1401         mono_set_defaults (mini_verbose, opt);
1402         domain = mini_init (argv [i], forced_version);
1403         
1404         switch (action) {
1405         case DO_REGRESSION:
1406                 if (mini_regression_list (mini_verbose, argc -i, argv + i)) {
1407                         g_print ("Regression ERRORS!\n");
1408                         mini_cleanup (domain);
1409                         return 1;
1410                 }
1411                 mini_cleanup (domain);
1412                 return 0;
1413         case DO_BENCH:
1414                 if (argc - i != 1 || mname == NULL) {
1415                         g_print ("Usage: mini --ncompile num --compile method assembly\n");
1416                         mini_cleanup (domain);
1417                         return 1;
1418                 }
1419                 aname = argv [i];
1420                 break;
1421         case DO_COMPILE:
1422                 if (argc - i != 1) {
1423                         mini_usage ();
1424                         mini_cleanup (domain);
1425                         return 1;
1426                 }
1427                 aname = argv [i];
1428                 break;
1429         case DO_DRAW:
1430                 if (argc - i != 1 || mname == NULL) {
1431                         mini_usage ();
1432                         mini_cleanup (domain);
1433                         return 1;
1434                 }
1435                 aname = argv [i];
1436                 break;
1437         default:
1438                 if (argc - i < 1) {
1439                         mini_usage ();
1440                         mini_cleanup (domain);
1441                         return 1;
1442                 }
1443                 aname = argv [i];
1444                 break;
1445         }
1446
1447         /* Parse gac loading options before loading assemblies. */
1448         if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
1449                 mono_config_parse (config_file);
1450         }
1451
1452 #ifdef MONO_JIT_INFO_TABLE_TEST
1453         if (test_jit_info_table)
1454                 jit_info_table_test (domain);
1455 #endif
1456
1457         assembly = mono_assembly_open (aname, &open_status);
1458         if (!assembly) {
1459                 fprintf (stderr, "Cannot open assembly '%s': %s.\n", aname, mono_image_strerror (open_status));
1460                 mini_cleanup (domain);
1461                 return 2;
1462         }
1463
1464         if (trace_options != NULL)
1465                 mono_trace_set_assembly (assembly);
1466
1467         if (mono_compile_aot || action == DO_EXEC) {
1468                 const char *error;
1469
1470                 //mono_set_rootdir ();
1471
1472                 error = mono_check_corlib_version ();
1473                 if (error) {
1474                         fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
1475                         fprintf (stderr, "Loaded from: %s\n",
1476                                 mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown");
1477                         fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.go-mono.com/daily.\n");
1478                         exit (1);
1479                 }
1480
1481 #ifdef PLATFORM_WIN32
1482                 /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
1483                 if (!enable_debugging && !mono_compile_aot && ((MonoCLIImageInfo*)(mono_assembly_get_image (assembly)->image_info))->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
1484                         FreeConsole ();
1485 #endif
1486
1487                 main_args.domain = domain;
1488                 main_args.file = aname;         
1489                 main_args.argc = argc - i;
1490                 main_args.argv = argv + i;
1491                 main_args.opts = opt;
1492                 main_args.aot_options = aot_options;
1493 #if RUN_IN_SUBTHREAD
1494                 mono_runtime_exec_managed_code (domain, main_thread_handler, &main_args);
1495 #else
1496                 main_thread_handler (&main_args);
1497                 mono_thread_manage ();
1498 #endif
1499                 mini_cleanup (domain);
1500
1501                 /* Look up return value from System.Environment.ExitCode */
1502                 i = mono_environment_exitcode_get ();
1503                 return i;
1504         } else if (action == DO_COMPILE) {
1505                 compile_all_methods (assembly, mini_verbose, opt);
1506                 mini_cleanup (domain);
1507                 return 0;
1508         } else if (action == DO_DEBUGGER) {
1509 #ifdef MONO_DEBUGGER_SUPPORTED
1510                 const char *error;
1511
1512                 error = mono_check_corlib_version ();
1513                 if (error) {
1514                         fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
1515                         fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.go-mono.com/daily.\n");
1516                         exit (1);
1517                 }
1518
1519                 mono_debugger_main (domain, assembly, argc - i, argv + i);
1520                 mini_cleanup (domain);
1521                 return 0;
1522 #else
1523                 return 1;
1524 #endif
1525         }
1526         desc = mono_method_desc_new (mname, 0);
1527         if (!desc) {
1528                 g_print ("Invalid method name %s\n", mname);
1529                 mini_cleanup (domain);
1530                 return 3;
1531         }
1532         method = mono_method_desc_search_in_image (desc, mono_assembly_get_image (assembly));
1533         if (!method) {
1534                 g_print ("Cannot find method %s\n", mname);
1535                 mini_cleanup (domain);
1536                 return 3;
1537         }
1538
1539         if (action == DO_DRAW) {
1540                 int part = 0;
1541
1542                 switch (mono_graph_options) {
1543                 case MONO_GRAPH_DTREE:
1544                         part = 1;
1545                         opt |= MONO_OPT_LOOP;
1546                         break;
1547                 case MONO_GRAPH_CFG_CODE:
1548                         part = 1;
1549                         break;
1550                 case MONO_GRAPH_CFG_SSA:
1551                         part = 2;
1552                         break;
1553                 case MONO_GRAPH_CFG_OPTCODE:
1554                         part = 3;
1555                         break;
1556                 default:
1557                         break;
1558                 }
1559
1560                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1561                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
1562                         MonoMethod *nm;
1563                         nm = mono_marshal_get_native_wrapper (method, TRUE);
1564                         cfg = mini_method_compile (nm, opt, mono_get_root_domain (), FALSE, FALSE, part);
1565                 }
1566                 else
1567                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, part);
1568                 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
1569                         g_warning ("no SSA info available (use -O=deadce)");
1570                         return 1;
1571                 }
1572                 mono_draw_graph (cfg, mono_graph_options);
1573                 mono_destroy_compile (cfg);
1574
1575         } else if (action == DO_BENCH) {
1576                 if (mini_stats_fd) {
1577                         const char *n;
1578                         double no_opt_time = 0.0;
1579                         GTimer *timer = g_timer_new ();
1580                         fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n", 
1581                                  mono_method_full_name (method, TRUE));
1582                         fprintf (mini_stats_fd, "@data = (\n");
1583                         fprintf (mini_stats_fd, "[");
1584                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
1585                                 opt = opt_sets [i];
1586                                 n = opt_descr (opt);
1587                                 if (!n [0])
1588                                         n = "none";
1589                                 fprintf (mini_stats_fd, "\"%s\",", n);
1590                         }
1591                         fprintf (mini_stats_fd, "],\n[");
1592
1593                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
1594                                 int j;
1595                                 double elapsed;
1596                                 opt = opt_sets [i];
1597                                 g_timer_start (timer);
1598                                 for (j = 0; j < count; ++j) {
1599                                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1600                                         mono_destroy_compile (cfg);
1601                                 }
1602                                 g_timer_stop (timer);
1603                                 elapsed = g_timer_elapsed (timer, NULL);
1604                                 if (!opt)
1605                                         no_opt_time = elapsed;
1606                                 fprintf (mini_stats_fd, "%f, ", elapsed);
1607                         }
1608                         fprintf (mini_stats_fd, "]");
1609                         if (no_opt_time > 0.0) {
1610                                 fprintf (mini_stats_fd, ", \n[");
1611                                 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) 
1612                                         fprintf (mini_stats_fd, "%f,", no_opt_time);
1613                                 fprintf (mini_stats_fd, "]");
1614                         }
1615                         fprintf (mini_stats_fd, ");\n");
1616                 } else {
1617                         for (i = 0; i < count; ++i) {
1618                                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1619                                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
1620                                         method = mono_marshal_get_native_wrapper (method, TRUE);
1621
1622                                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1623                                 mono_destroy_compile (cfg);
1624                         }
1625                 }
1626         } else {
1627                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1628                 mono_destroy_compile (cfg);
1629         }
1630
1631         mini_cleanup (domain);
1632         return 0;
1633 }
1634
1635 MonoDomain * 
1636 mono_jit_init (const char *file)
1637 {
1638         return mini_init (file, NULL);
1639 }
1640
1641 /**
1642  * mono_jit_init_version:
1643  * @file: the initial assembly to load
1644  * @runtime_version: the version of the runtime to load
1645  *
1646  * Use this version when you want to force a particular runtime
1647  * version to be used.  By default Mono will pick the runtime that is
1648  * referenced by the initial assembly (specified in @file), this
1649  * routine allows programmers to specify the actual runtime to be used
1650  * as the initial runtime is inherited by all future assemblies loaded
1651  * (since Mono does not support having more than one mscorlib runtime
1652  * loaded at once).
1653  *
1654  * The @runtime_version can be one of these strings: "v1.1.4322" for
1655  * the 1.1 runtime or "v2.0.50727"  for the 2.0 runtime. 
1656  *
1657  * Returns: the MonoDomain representing the domain where the assembly
1658  * was loaded.
1659  */
1660 MonoDomain * 
1661 mono_jit_init_version (const char *file, const char *runtime_version)
1662 {
1663         return mini_init (file, runtime_version);
1664 }
1665
1666 void        
1667 mono_jit_cleanup (MonoDomain *domain)
1668 {
1669         mini_cleanup (domain);
1670 }