2008-06-01 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / mini / driver.c
1 /*
2  * driver.c: The new mono JIT compiler.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002-2003 Ximian, Inc.
9  * (C) 2003-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 #if defined(__arm__) && defined(__ARM_EABI__)
1035 /* Redefine ARCHITECTURE to include more information */
1036 #undef ARCHITECTURE
1037 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
1038 #define ARCHITECTURE "armel"
1039 #else
1040 #define ARCHITECTURE "armeb"
1041 #endif
1042 #endif
1043
1044 static const char info[] =
1045 #ifdef HAVE_KW_THREAD
1046         "\tTLS:           __thread\n"
1047 #else
1048         "\tTLS:           normal\n"
1049 #endif /* HAVE_KW_THREAD */
1050         "\tGC:            " USED_GC_NAME "\n"
1051 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
1052     "\tSIGSEGV:       altstack\n"
1053 #else
1054     "\tSIGSEGV:       normal\n"
1055 #endif
1056 #ifdef HAVE_EPOLL
1057     "\tNotifications: epoll\n"
1058 #else
1059     "\tNotification:  Thread + polling\n"
1060 #endif
1061         "\tArchitecture:  " ARCHITECTURE "\n"
1062         "\tDisabled:      " DISABLED_FEATURES "\n"
1063         "";
1064
1065 #ifndef MONO_ARCH_AOT_SUPPORTED
1066 #define error_if_aot_unsupported() do {fprintf (stderr, "AOT compilation is not supported on this platform.\n"); exit (1);} while (0)
1067 #else
1068 #define error_if_aot_unsupported()
1069 #endif
1070
1071 #ifdef PLATFORM_WIN32
1072 BOOL APIENTRY DllMain (HMODULE module_handle, DWORD reason, LPVOID reserved)
1073 {
1074         if (!GC_DllMain (module_handle, reason, reserved))
1075                 return FALSE;
1076
1077         switch (reason)
1078         {
1079         case DLL_PROCESS_ATTACH:
1080                 mono_module_handle = module_handle;
1081                 mono_install_runtime_load (mini_init);
1082                 break;
1083         case DLL_PROCESS_DETACH:
1084                 if (coree_module_handle)
1085                         FreeLibrary (coree_module_handle);
1086                 break;
1087         }
1088         return TRUE;
1089 }
1090 #endif
1091
1092 int
1093 mono_main (int argc, char* argv[])
1094 {
1095         MainThreadArgs main_args;
1096         MonoAssembly *assembly;
1097         MonoMethodDesc *desc;
1098         MonoMethod *method;
1099         MonoCompile *cfg;
1100         MonoDomain *domain;
1101         MonoImageOpenStatus open_status;
1102         const char* aname, *mname = NULL;
1103         char *config_file = NULL;
1104         int i, count = 1;
1105         int enable_debugging = FALSE;
1106         guint32 opt, action = DO_EXEC;
1107         MonoGraphOptions mono_graph_options = 0;
1108         int mini_verbose = 0;
1109         gboolean enable_profile = FALSE;
1110         char *trace_options = NULL;
1111         char *profile_options = NULL;
1112         char *aot_options = NULL;
1113         char *forced_version = NULL;
1114 #ifdef MONO_JIT_INFO_TABLE_TEST
1115         int test_jit_info_table = FALSE;
1116 #endif
1117
1118         setlocale (LC_ALL, "");
1119
1120 #if HAVE_SCHED_SETAFFINITY
1121         if (getenv ("MONO_NO_SMP")) {
1122                 unsigned long proc_mask = 1;
1123                 sched_setaffinity (getpid(), sizeof (unsigned long), (gpointer)&proc_mask);
1124         }
1125 #endif
1126         if (!g_thread_supported ())
1127                 g_thread_init (NULL);
1128
1129         if (mono_running_on_valgrind () && getenv ("MONO_VALGRIND_LEAK_CHECK")) {
1130                 GMemVTable mem_vtable;
1131
1132                 /* 
1133                  * Instruct glib to use the system allocation functions so valgrind
1134                  * can track the memory allocated by the g_... functions.
1135                  */
1136                 memset (&mem_vtable, 0, sizeof (mem_vtable));
1137                 mem_vtable.malloc = malloc;
1138                 mem_vtable.realloc = realloc;
1139                 mem_vtable.free = free;
1140                 mem_vtable.calloc = calloc;
1141
1142                 g_mem_set_vtable (&mem_vtable);
1143         }
1144
1145         g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
1146         g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
1147
1148         opt = parse_optimizations (NULL);
1149
1150         for (i = 1; i < argc; ++i) {
1151                 if (argv [i] [0] != '-')
1152                         break;
1153                 if (strcmp (argv [i], "--regression") == 0) {
1154                         action = DO_REGRESSION;
1155                 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
1156                         mini_verbose++;
1157                 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
1158                         g_print ("Mono JIT compiler version %s (%s)\nCopyright (C) 2002-2008 Novell, Inc and Contributors. www.mono-project.com\n", VERSION, FULL_VERSION);
1159                         g_print (info);
1160                         if (mini_verbose) {
1161                                 const char *cerror;
1162                                 const char *clibpath;
1163                                 mono_init ("mono");
1164                                 cerror = mono_check_corlib_version ();
1165                                 clibpath = mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown";
1166                                 if (cerror) {
1167                                         g_print ("The currently installed mscorlib doesn't match this runtime version.\n");
1168                                         g_print ("The error is: %s\n", cerror);
1169                                         g_print ("mscorlib.dll loaded at: %s\n", clibpath);
1170                                         return 1;
1171                                 }
1172                         }
1173                         return 0;
1174                 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
1175                         mini_usage ();
1176                         return 0;
1177                 } else if (strcmp (argv [i], "--help-trace") == 0){
1178                         mini_trace_usage ();
1179                         return 0;
1180                 } else if (strcmp (argv [i], "--help-devel") == 0){
1181                         mini_usage_jitdeveloper ();
1182                         return 0;
1183                 } else if (strcmp (argv [i], "--help-debug") == 0){
1184                         mini_debug_usage ();
1185                         return 0;
1186                 } else if (strcmp (argv [i], "--list-opt") == 0){
1187                         mini_usage_list_opt ();
1188                         return 0;
1189                 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
1190                         if (i + 1 >= argc){
1191                                 fprintf (stderr, "error: --statfile requires a filename argument\n");
1192                                 return 1;
1193                         }
1194                         mini_stats_fd = fopen (argv [++i], "w+");
1195                 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
1196                         opt = parse_optimizations (argv [i] + 11);
1197                 } else if (strncmp (argv [i], "-O=", 3) == 0) {
1198                         opt = parse_optimizations (argv [i] + 3);
1199                 } else if (strcmp (argv [i], "--config") == 0) {
1200                         if (i +1 >= argc){
1201                                 fprintf (stderr, "error: --config requires a filename argument\n");
1202                                 return 1;
1203                         }
1204                         config_file = argv [++i];
1205                 } else if (strcmp (argv [i], "--ncompile") == 0) {
1206                         if (i + 1 >= argc){
1207                                 fprintf (stderr, "error: --ncompile requires an argument\n");
1208                                 return 1;
1209                         }
1210                         count = atoi (argv [++i]);
1211                         action = DO_BENCH;
1212                 } else if (strcmp (argv [i], "--trace") == 0) {
1213                         trace_options = (char*)"";
1214                 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
1215                         trace_options = &argv [i][8];
1216                 } else if (strcmp (argv [i], "--breakonex") == 0) {
1217                         mono_break_on_exc = TRUE;
1218                 } else if (strcmp (argv [i], "--break") == 0) {
1219                         if (i+1 >= argc){
1220                                 fprintf (stderr, "Missing method name in --break command line option\n");
1221                                 return 1;
1222                         }
1223                         
1224                         if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
1225                                 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
1226                 } else if (strcmp (argv [i], "--break-at-bb") == 0) {
1227                         if (i + 2 >= argc) {
1228                                 fprintf (stderr, "Missing method name or bb num in --break-at-bb command line option.");
1229                                 return 1;
1230                         }
1231                         mono_break_at_bb_method = mono_method_desc_new (argv [++i], TRUE);
1232                         if (mono_break_at_bb_method == NULL) {
1233                                 fprintf (stderr, "Method name is in a bad format in --break-at-bb command line option.");
1234                                 return 1;
1235                         }
1236                         mono_break_at_bb_bb_num = atoi (argv [++i]);
1237                 } else if (strcmp (argv [i], "--inject-async-exc") == 0) {
1238                         if (i + 2 >= argc) {
1239                                 fprintf (stderr, "Missing method name or position in --inject-async-exc command line option\n");
1240                                 return 1;
1241                         }
1242                         mono_inject_async_exc_method = mono_method_desc_new (argv [++i], TRUE);
1243                         if (mono_inject_async_exc_method == NULL) {
1244                                 fprintf (stderr, "Method name is in a bad format in --inject-async-exc command line option\n");
1245                                 return 1;
1246                         }
1247                         mono_inject_async_exc_pos = atoi (argv [++i]);
1248                 } else if (strcmp (argv [i], "--verify-all") == 0) {
1249                         mono_verifier_enable_verify_all ();
1250                 } else if (strcmp (argv [i], "--print-vtable") == 0) {
1251                         mono_print_vtable = TRUE;
1252                 } else if (strcmp (argv [i], "--stats") == 0) {
1253                         mono_counters_enable (-1);
1254                         mono_stats.enabled = TRUE;
1255                         mono_jit_stats.enabled = TRUE;
1256 #ifndef DISABLE_AOT
1257                 } else if (strcmp (argv [i], "--aot") == 0) {
1258                         error_if_aot_unsupported ();
1259                         mono_compile_aot = TRUE;
1260                 } else if (strncmp (argv [i], "--aot=", 6) == 0) {
1261                         error_if_aot_unsupported ();
1262                         mono_compile_aot = TRUE;
1263                         aot_options = &argv [i][6];
1264 #endif
1265                 } else if (strcmp (argv [i], "--compile-all") == 0) {
1266                         action = DO_COMPILE;
1267                 } else if (strncmp (argv [i], "--runtime=", 10) == 0) {
1268                         forced_version = &argv [i][10];
1269                 } else if (strcmp (argv [i], "--profile") == 0) {
1270                         enable_profile = TRUE;
1271                         profile_options = NULL;
1272                 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
1273                         enable_profile = TRUE;
1274                         profile_options = argv [i] + 10;
1275                 } else if (strcmp (argv [i], "--compile") == 0) {
1276                         if (i + 1 >= argc){
1277                                 fprintf (stderr, "error: --compile option requires a method name argument\n");
1278                                 return 1;
1279                         }
1280                         
1281                         mname = argv [++i];
1282                         action = DO_BENCH;
1283                 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
1284                         if (i + 1 >= argc){
1285                                 fprintf (stderr, "error: --graph option requires a method name argument\n");
1286                                 return 1;
1287                         }
1288                         
1289                         mono_graph_options = mono_parse_graph_options (argv [i] + 8);
1290                         mname = argv [++i];
1291                         action = DO_DRAW;
1292                 } else if (strcmp (argv [i], "--graph") == 0) {
1293                         if (i + 1 >= argc){
1294                                 fprintf (stderr, "error: --graph option requires a method name argument\n");
1295                                 return 1;
1296                         }
1297                         
1298                         mname = argv [++i];
1299                         mono_graph_options = MONO_GRAPH_CFG;
1300                         action = DO_DRAW;
1301                 } else if (strcmp (argv [i], "--debug") == 0) {
1302                         enable_debugging = TRUE;
1303                 } else if (strncmp (argv [i], "--debug=", 8) == 0) {
1304                         enable_debugging = TRUE;
1305                         if (!parse_debug_options (argv [i] + 8))
1306                                 return 1;
1307                 } else if (strcmp (argv [i], "--security") == 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_CAS);
1312                         mono_activate_security_manager ();
1313                 } else if (strncmp (argv [i], "--security=", 11) == 0) {
1314                         if (strcmp (argv [i] + 11, "temporary-smcs-hack") == 0) {
1315                                 mono_security_set_mode (MONO_SECURITY_MODE_SMCS_HACK);
1316                         } else if (strcmp (argv [i] + 11, "core-clr") == 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_CORE_CLR);
1321                         } else if (strcmp (argv [i] + 11, "core-clr-test") == 0) {
1322                                 /* fixme should we enable verifiable code here?*/
1323                                 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
1324                                 mono_security_core_clr_test = TRUE;
1325                         } else if (strcmp (argv [i] + 11, "cas") == 0){
1326                                 /* fixme enable verifiable code when the verifier works with 2.0
1327                                  * mini_verifier_set_mode (MINI_VERIFIER_MODE_VERIFIABLE);
1328                                  */
1329                                 mono_security_set_mode (MONO_SECURITY_MODE_CAS);
1330                                 mono_activate_security_manager ();
1331                         } else  if (strcmp (argv [i] + 11, "validil") == 0) {
1332                                 mono_verifier_set_mode (MONO_VERIFIER_MODE_VALID);
1333                         } else  if (strcmp (argv [i] + 11, "verifiable") == 0) {
1334                                 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
1335                         } else  {
1336                                 fprintf (stderr, "error: --security= option has invalid argument (cas, core-clr, verifiable or validil)\n");
1337                                 return 1;
1338                         }
1339                 } else if (strcmp (argv [i], "--desktop") == 0) {
1340 #if defined (HAVE_BOEHM_GC)
1341                         GC_dont_expand = 1;
1342 #endif
1343                         /* Put desktop-specific optimizations here */
1344                 } else if (strcmp (argv [i], "--server") == 0){
1345                         /* Put server-specific optimizations here */
1346                 } else if (strcmp (argv [i], "--inside-mdb") == 0) {
1347                         action = DO_DEBUGGER;
1348                 } else if (strncmp (argv [i], "--wapi=", 7) == 0) {
1349                         if (strcmp (argv [i] + 7, "hps") == 0) {
1350                                 return mini_wapi_hps (argc - i, argv + i);
1351                         } else if (strcmp (argv [i] + 7, "semdel") == 0) {
1352                                 return mini_wapi_semdel (argc - i, argv + i);
1353                         } else if (strcmp (argv [i] + 7, "seminfo") == 0) {
1354                                 return mini_wapi_seminfo (argc - i, argv + i);
1355                         } else {
1356                                 fprintf (stderr, "Invalid --wapi suboption: '%s'\n", argv [i]);
1357                                 return 1;
1358                         }
1359 #ifdef MONO_JIT_INFO_TABLE_TEST
1360                 } else if (strcmp (argv [i], "--test-jit-info-table") == 0) {
1361                         test_jit_info_table = TRUE;
1362 #endif
1363                 } else {
1364                         fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
1365                         return 1;
1366                 }
1367         }
1368
1369         if (!argv [i]) {
1370                 mini_usage ();
1371                 return 1;
1372         }
1373
1374         if ((action == DO_EXEC) && mono_debug_using_mono_debugger ())
1375                 action = DO_DEBUGGER;
1376
1377         if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
1378                 g_set_prgname (argv[i]);
1379         }
1380
1381         if (enable_profile) {
1382                 /* Needed because of TLS accesses in mono_profiler_load () */
1383                 mono_gc_base_init ();
1384                 mono_profiler_load (profile_options);
1385         }
1386
1387         if (trace_options != NULL){
1388                 /* 
1389                  * Need to call this before mini_init () so we can trace methods 
1390                  * compiled there too.
1391                  */
1392                 mono_jit_trace_calls = mono_trace_parse_options (trace_options);
1393                 if (mono_jit_trace_calls == NULL)
1394                         exit (1);
1395         }
1396
1397         if (action == DO_DEBUGGER) {
1398                 enable_debugging = TRUE;
1399
1400 #ifdef MONO_DEBUGGER_SUPPORTED
1401                 mono_debug_init (MONO_DEBUG_FORMAT_DEBUGGER);
1402                 mono_debugger_init ();
1403 #else
1404                 g_print ("The Mono Debugger is not supported on this platform.\n");
1405                 return 1;
1406 #endif
1407         } else if (enable_debugging)
1408                 mono_debug_init (MONO_DEBUG_FORMAT_MONO);
1409
1410         mono_set_defaults (mini_verbose, opt);
1411         mono_setup_vtable_in_class_init = FALSE;
1412         domain = mini_init (argv [i], forced_version);
1413         
1414         switch (action) {
1415         case DO_REGRESSION:
1416                 if (mini_regression_list (mini_verbose, argc -i, argv + i)) {
1417                         g_print ("Regression ERRORS!\n");
1418                         mini_cleanup (domain);
1419                         return 1;
1420                 }
1421                 mini_cleanup (domain);
1422                 return 0;
1423         case DO_BENCH:
1424                 if (argc - i != 1 || mname == NULL) {
1425                         g_print ("Usage: mini --ncompile num --compile method assembly\n");
1426                         mini_cleanup (domain);
1427                         return 1;
1428                 }
1429                 aname = argv [i];
1430                 break;
1431         case DO_COMPILE:
1432                 if (argc - i != 1) {
1433                         mini_usage ();
1434                         mini_cleanup (domain);
1435                         return 1;
1436                 }
1437                 aname = argv [i];
1438                 break;
1439         case DO_DRAW:
1440                 if (argc - i != 1 || mname == NULL) {
1441                         mini_usage ();
1442                         mini_cleanup (domain);
1443                         return 1;
1444                 }
1445                 aname = argv [i];
1446                 break;
1447         default:
1448                 if (argc - i < 1) {
1449                         mini_usage ();
1450                         mini_cleanup (domain);
1451                         return 1;
1452                 }
1453                 aname = argv [i];
1454                 break;
1455         }
1456
1457         /* Parse gac loading options before loading assemblies. */
1458         if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
1459                 mono_config_parse (config_file);
1460         }
1461
1462 #ifdef MONO_JIT_INFO_TABLE_TEST
1463         if (test_jit_info_table)
1464                 jit_info_table_test (domain);
1465 #endif
1466
1467         assembly = mono_assembly_open (aname, &open_status);
1468         if (!assembly) {
1469                 fprintf (stderr, "Cannot open assembly '%s': %s.\n", aname, mono_image_strerror (open_status));
1470                 mini_cleanup (domain);
1471                 return 2;
1472         }
1473
1474         if (trace_options != NULL)
1475                 mono_trace_set_assembly (assembly);
1476
1477         if (mono_compile_aot || action == DO_EXEC) {
1478                 const char *error;
1479
1480                 //mono_set_rootdir ();
1481
1482                 error = mono_check_corlib_version ();
1483                 if (error) {
1484                         fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
1485                         fprintf (stderr, "Loaded from: %s\n",
1486                                 mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown");
1487                         fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.go-mono.com/daily.\n");
1488                         exit (1);
1489                 }
1490
1491 #ifdef PLATFORM_WIN32
1492                 /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
1493                 if (!enable_debugging && !mono_compile_aot && ((MonoCLIImageInfo*)(mono_assembly_get_image (assembly)->image_info))->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
1494                         FreeConsole ();
1495 #endif
1496
1497                 main_args.domain = domain;
1498                 main_args.file = aname;         
1499                 main_args.argc = argc - i;
1500                 main_args.argv = argv + i;
1501                 main_args.opts = opt;
1502                 main_args.aot_options = aot_options;
1503 #if RUN_IN_SUBTHREAD
1504                 mono_runtime_exec_managed_code (domain, main_thread_handler, &main_args);
1505 #else
1506                 main_thread_handler (&main_args);
1507                 mono_thread_manage ();
1508 #endif
1509                 mini_cleanup (domain);
1510
1511                 /* Look up return value from System.Environment.ExitCode */
1512                 i = mono_environment_exitcode_get ();
1513                 return i;
1514         } else if (action == DO_COMPILE) {
1515                 compile_all_methods (assembly, mini_verbose, opt);
1516                 mini_cleanup (domain);
1517                 return 0;
1518         } else if (action == DO_DEBUGGER) {
1519 #ifdef MONO_DEBUGGER_SUPPORTED
1520                 const char *error;
1521
1522                 error = mono_check_corlib_version ();
1523                 if (error) {
1524                         fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
1525                         fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.go-mono.com/daily.\n");
1526                         exit (1);
1527                 }
1528
1529                 mono_debugger_main (domain, assembly, argc - i, argv + i);
1530                 mini_cleanup (domain);
1531                 return 0;
1532 #else
1533                 return 1;
1534 #endif
1535         }
1536         desc = mono_method_desc_new (mname, 0);
1537         if (!desc) {
1538                 g_print ("Invalid method name %s\n", mname);
1539                 mini_cleanup (domain);
1540                 return 3;
1541         }
1542         method = mono_method_desc_search_in_image (desc, mono_assembly_get_image (assembly));
1543         if (!method) {
1544                 g_print ("Cannot find method %s\n", mname);
1545                 mini_cleanup (domain);
1546                 return 3;
1547         }
1548
1549         if (action == DO_DRAW) {
1550                 int part = 0;
1551
1552                 switch (mono_graph_options) {
1553                 case MONO_GRAPH_DTREE:
1554                         part = 1;
1555                         opt |= MONO_OPT_LOOP;
1556                         break;
1557                 case MONO_GRAPH_CFG_CODE:
1558                         part = 1;
1559                         break;
1560                 case MONO_GRAPH_CFG_SSA:
1561                         part = 2;
1562                         break;
1563                 case MONO_GRAPH_CFG_OPTCODE:
1564                         part = 3;
1565                         break;
1566                 default:
1567                         break;
1568                 }
1569
1570                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1571                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
1572                         MonoMethod *nm;
1573                         nm = mono_marshal_get_native_wrapper (method, TRUE);
1574                         cfg = mini_method_compile (nm, opt, mono_get_root_domain (), FALSE, FALSE, part);
1575                 }
1576                 else
1577                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, part);
1578                 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
1579                         g_warning ("no SSA info available (use -O=deadce)");
1580                         return 1;
1581                 }
1582                 mono_draw_graph (cfg, mono_graph_options);
1583                 mono_destroy_compile (cfg);
1584
1585         } else if (action == DO_BENCH) {
1586                 if (mini_stats_fd) {
1587                         const char *n;
1588                         double no_opt_time = 0.0;
1589                         GTimer *timer = g_timer_new ();
1590                         fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n", 
1591                                  mono_method_full_name (method, TRUE));
1592                         fprintf (mini_stats_fd, "@data = (\n");
1593                         fprintf (mini_stats_fd, "[");
1594                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
1595                                 opt = opt_sets [i];
1596                                 n = opt_descr (opt);
1597                                 if (!n [0])
1598                                         n = "none";
1599                                 fprintf (mini_stats_fd, "\"%s\",", n);
1600                         }
1601                         fprintf (mini_stats_fd, "],\n[");
1602
1603                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
1604                                 int j;
1605                                 double elapsed;
1606                                 opt = opt_sets [i];
1607                                 g_timer_start (timer);
1608                                 for (j = 0; j < count; ++j) {
1609                                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1610                                         mono_destroy_compile (cfg);
1611                                 }
1612                                 g_timer_stop (timer);
1613                                 elapsed = g_timer_elapsed (timer, NULL);
1614                                 if (!opt)
1615                                         no_opt_time = elapsed;
1616                                 fprintf (mini_stats_fd, "%f, ", elapsed);
1617                         }
1618                         fprintf (mini_stats_fd, "]");
1619                         if (no_opt_time > 0.0) {
1620                                 fprintf (mini_stats_fd, ", \n[");
1621                                 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) 
1622                                         fprintf (mini_stats_fd, "%f,", no_opt_time);
1623                                 fprintf (mini_stats_fd, "]");
1624                         }
1625                         fprintf (mini_stats_fd, ");\n");
1626                 } else {
1627                         for (i = 0; i < count; ++i) {
1628                                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1629                                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
1630                                         method = mono_marshal_get_native_wrapper (method, TRUE);
1631
1632                                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1633                                 mono_destroy_compile (cfg);
1634                         }
1635                 }
1636         } else {
1637                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
1638                 mono_destroy_compile (cfg);
1639         }
1640
1641         mini_cleanup (domain);
1642         return 0;
1643 }
1644
1645 MonoDomain * 
1646 mono_jit_init (const char *file)
1647 {
1648         return mini_init (file, NULL);
1649 }
1650
1651 /**
1652  * mono_jit_init_version:
1653  * @file: the initial assembly to load
1654  * @runtime_version: the version of the runtime to load
1655  *
1656  * Use this version when you want to force a particular runtime
1657  * version to be used.  By default Mono will pick the runtime that is
1658  * referenced by the initial assembly (specified in @file), this
1659  * routine allows programmers to specify the actual runtime to be used
1660  * as the initial runtime is inherited by all future assemblies loaded
1661  * (since Mono does not support having more than one mscorlib runtime
1662  * loaded at once).
1663  *
1664  * The @runtime_version can be one of these strings: "v1.1.4322" for
1665  * the 1.1 runtime or "v2.0.50727"  for the 2.0 runtime. 
1666  *
1667  * Returns: the MonoDomain representing the domain where the assembly
1668  * was loaded.
1669  */
1670 MonoDomain * 
1671 mono_jit_init_version (const char *file, const char *runtime_version)
1672 {
1673         return mini_init (file, runtime_version);
1674 }
1675
1676 void        
1677 mono_jit_cleanup (MonoDomain *domain)
1678 {
1679         mini_cleanup (domain);
1680 }