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