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