[tests] Reenable enum equals test on interpreter (#18673)
[mono-project.git] / mono / mini / driver.c
blob3971f03ec9faa9d94d367c6033fd779a544172a2
1 /**
2 * \file
3 * The new mono JIT compiler.
5 * Author:
6 * Paolo Molaro (lupus@ximian.com)
7 * Dietmar Maurer (dietmar@ximian.com)
9 * (C) 2002-2003 Ximian, Inc.
10 * (C) 2003-2006 Novell, Inc.
11 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14 #include <config.h>
15 #include <signal.h>
16 #if HAVE_SCHED_SETAFFINITY
17 #include <sched.h>
18 #endif
19 #ifdef HAVE_UNISTD_H
20 #include <unistd.h>
21 #endif
23 #include <mono/metadata/assembly-internals.h>
24 #include <mono/metadata/image-internals.h>
25 #include <mono/metadata/loader.h>
26 #include <mono/metadata/tabledefs.h>
27 #include <mono/metadata/class.h>
28 #include <mono/metadata/object.h>
29 #include <mono/metadata/exception.h>
30 #include <mono/metadata/opcodes.h>
31 #include <mono/metadata/mono-endian.h>
32 #include <mono/metadata/tokentype.h>
33 #include <mono/metadata/reflection-internals.h>
34 #include <mono/metadata/tabledefs.h>
35 #include <mono/metadata/threads.h>
36 #include <mono/metadata/marshal.h>
37 #include <mono/metadata/appdomain.h>
38 #include <mono/metadata/debug-helpers.h>
39 #include <mono/metadata/profiler-private.h>
40 #include <mono/metadata/mono-config.h>
41 #include <mono/metadata/environment.h>
42 #include <mono/metadata/verify.h>
43 #include <mono/metadata/verify-internals.h>
44 #include <mono/metadata/mono-debug.h>
45 #include <mono/metadata/security-manager.h>
46 #include <mono/metadata/security-core-clr.h>
47 #include <mono/metadata/gc-internals.h>
48 #include <mono/metadata/coree.h>
49 #include <mono/metadata/attach.h>
50 #include <mono/metadata/w32process.h>
51 #include "mono/utils/mono-counters.h"
52 #include "mono/utils/mono-hwcap.h"
53 #include "mono/utils/mono-logger-internals.h"
54 #include "mono/metadata/w32handle.h"
55 #include "mono/metadata/callspec.h"
56 #include "mono/metadata/custom-attrs-internals.h"
58 #include "mini.h"
59 #include "jit.h"
60 #include "aot-compiler.h"
61 #include "aot-runtime.h"
62 #include "mini-runtime.h"
63 #include "interp/interp.h"
65 #include <string.h>
66 #include <ctype.h>
67 #include <locale.h>
68 #include "version.h"
69 #include "debugger-agent.h"
70 #if TARGET_OSX
71 # include <sys/resource.h>
72 #endif
74 static FILE *mini_stats_fd;
76 static void mini_usage (void);
77 static void mono_runtime_set_execution_mode (int mode);
78 static void mono_runtime_set_execution_mode_full (int mode, gboolean override);
79 static int mono_jit_exec_internal (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[]);
81 #ifdef HOST_WIN32
82 /* Need this to determine whether to detach console */
83 #include <mono/metadata/cil-coff.h>
84 /* This turns off command line globbing under win32 */
85 int _CRT_glob = 0;
86 #endif
88 typedef void (*OptFunc) (const char *p);
90 #undef OPTFLAG
92 // This, instead of an array of pointers, to optimize away a pointer and a relocation per string.
93 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
94 #define MSGSTRFIELD1(line) str##line
96 static const struct msgstr_t {
97 #define OPTFLAG(id,shift,name,desc) char MSGSTRFIELD(__LINE__) [sizeof (name) + sizeof (desc)];
98 #include "optflags-def.h"
99 #undef OPTFLAG
100 } opstr = {
101 #define OPTFLAG(id,shift,name,desc) name "\0" desc,
102 #include "optflags-def.h"
103 #undef OPTFLAG
105 static const gint16 opt_names [] = {
106 #define OPTFLAG(id,shift,name,desc) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
107 #include "optflags-def.h"
108 #undef OPTFLAG
111 #define optflag_get_name(id) ((const char*)&opstr + opt_names [(id)])
112 #define optflag_get_desc(id) (optflag_get_name(id) + 1 + strlen (optflag_get_name(id)))
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_DEADCE | \
121 MONO_OPT_BRANCH | \
122 MONO_OPT_LINEARS | \
123 MONO_OPT_INTRINS | \
124 MONO_OPT_LOOP | \
125 MONO_OPT_EXCEPTION | \
126 MONO_OPT_CMOV | \
127 MONO_OPT_GSHARED | \
128 MONO_OPT_SIMD | \
129 MONO_OPT_ALIAS_ANALYSIS | \
130 MONO_OPT_AOT | \
131 MONO_OPT_FLOAT32)
133 #define EXCLUDED_FROM_ALL (MONO_OPT_SHARED | MONO_OPT_PRECOMP | MONO_OPT_UNSAFE | MONO_OPT_GSHAREDVT)
135 static char *mono_parse_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend);
136 static char *mono_parse_response_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend);
138 static guint32
139 parse_optimizations (guint32 opt, const char* p, gboolean cpu_opts)
141 guint32 exclude = 0;
142 const char *n;
143 int i, invert;
144 char **parts, **ptr;
146 /* Initialize the hwcap module if necessary. */
147 mono_hwcap_init ();
149 /* call out to cpu detection code here that sets the defaults ... */
150 if (cpu_opts) {
151 #ifndef MONO_CROSS_COMPILE
152 opt |= mono_arch_cpu_optimizations (&exclude);
153 opt &= ~exclude;
154 #endif
156 if (!p)
157 return opt;
159 parts = g_strsplit (p, ",", -1);
160 for (ptr = parts; ptr && *ptr; ptr ++) {
161 char *arg = *ptr;
162 char *p = arg;
164 if (*p == '-') {
165 p++;
166 invert = TRUE;
167 } else {
168 invert = FALSE;
170 for (i = 0; i < G_N_ELEMENTS (opt_names) && optflag_get_name (i); ++i) {
171 n = optflag_get_name (i);
172 if (!strcmp (p, n)) {
173 if (invert)
174 opt &= ~ (1 << i);
175 else
176 opt |= 1 << i;
177 break;
180 if (i == G_N_ELEMENTS (opt_names) || !optflag_get_name (i)) {
181 if (strncmp (p, "all", 3) == 0) {
182 if (invert)
183 opt = 0;
184 else
185 opt = ~(EXCLUDED_FROM_ALL | exclude);
186 } else {
187 fprintf (stderr, "Invalid optimization name `%s'\n", p);
188 exit (1);
192 g_free (arg);
194 g_free (parts);
196 return opt;
199 static gboolean
200 parse_debug_options (const char* p)
202 MonoDebugOptions *opt = mini_get_debug_options ();
204 do {
205 if (!*p) {
206 fprintf (stderr, "Syntax error; expected debug option name\n");
207 return FALSE;
210 if (!strncmp (p, "casts", 5)) {
211 opt->better_cast_details = TRUE;
212 p += 5;
213 } else if (!strncmp (p, "mdb-optimizations", 17)) {
214 opt->mdb_optimizations = TRUE;
215 p += 17;
216 } else if (!strncmp (p, "gdb", 3)) {
217 opt->gdb = TRUE;
218 p += 3;
219 } else {
220 fprintf (stderr, "Invalid debug option `%s', use --help-debug for details\n", p);
221 return FALSE;
224 if (*p == ',') {
225 p++;
226 if (!*p) {
227 fprintf (stderr, "Syntax error; expected debug option name\n");
228 return FALSE;
231 } while (*p);
233 return TRUE;
236 typedef struct {
237 const char name [6];
238 const char desc [18];
239 MonoGraphOptions value;
240 } GraphName;
242 static const GraphName
243 graph_names [] = {
244 {"cfg", "Control Flow", MONO_GRAPH_CFG},
245 {"dtree", "Dominator Tree", MONO_GRAPH_DTREE},
246 {"code", "CFG showing code", MONO_GRAPH_CFG_CODE},
247 {"ssa", "CFG after SSA", MONO_GRAPH_CFG_SSA},
248 {"optc", "CFG after IR opts", MONO_GRAPH_CFG_OPTCODE}
251 static MonoGraphOptions
252 mono_parse_graph_options (const char* p)
254 const char *n;
255 int i, len;
257 for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
258 n = graph_names [i].name;
259 len = strlen (n);
260 if (strncmp (p, n, len) == 0)
261 return graph_names [i].value;
264 fprintf (stderr, "Invalid graph name provided: %s\n", p);
265 exit (1);
269 * mono_parse_default_optimizations:
272 mono_parse_default_optimizations (const char* p)
274 guint32 opt;
276 opt = parse_optimizations (DEFAULT_OPTIMIZATIONS, p, TRUE);
277 return opt;
280 char*
281 mono_opt_descr (guint32 flags) {
282 GString *str = g_string_new ("");
283 int i;
284 gboolean need_comma;
286 need_comma = FALSE;
287 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
288 if (flags & (1 << i) && optflag_get_name (i)) {
289 if (need_comma)
290 g_string_append_c (str, ',');
291 g_string_append (str, optflag_get_name (i));
292 need_comma = TRUE;
295 return g_string_free (str, FALSE);
298 static const guint32
299 opt_sets [] = {
301 MONO_OPT_PEEPHOLE,
302 MONO_OPT_BRANCH,
303 MONO_OPT_CFOLD,
304 MONO_OPT_FCMOV,
305 MONO_OPT_ALIAS_ANALYSIS,
306 #ifdef MONO_ARCH_SIMD_INTRINSICS
307 MONO_OPT_SIMD | MONO_OPT_INTRINS,
308 MONO_OPT_SSE2,
309 MONO_OPT_SIMD | MONO_OPT_SSE2 | MONO_OPT_INTRINS,
310 #endif
311 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS,
312 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS | MONO_OPT_ALIAS_ANALYSIS,
313 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS,
314 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP,
315 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_CFOLD,
316 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE,
317 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_ALIAS_ANALYSIS,
318 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,
319 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_TAILCALL,
320 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,
321 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,
322 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_CMOV,
323 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,
324 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,
325 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,
326 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_EXCEPTION | MONO_OPT_CMOV,
327 DEFAULT_OPTIMIZATIONS,
330 static const guint32
331 interp_opt_sets [] = {
332 INTERP_OPT_NONE,
333 INTERP_OPT_INLINE,
334 INTERP_OPT_CPROP,
335 INTERP_OPT_SUPER_INSTRUCTIONS,
336 INTERP_OPT_INLINE | INTERP_OPT_CPROP,
337 INTERP_OPT_INLINE | INTERP_OPT_SUPER_INSTRUCTIONS,
338 INTERP_OPT_CPROP | INTERP_OPT_SUPER_INSTRUCTIONS,
339 INTERP_OPT_INLINE | INTERP_OPT_CPROP | INTERP_OPT_SUPER_INSTRUCTIONS,
342 static const char* const
343 interp_opflags_names [] = {
344 "inline",
345 "cprop",
346 "super-insn"
349 static const char*
350 interp_optflag_get_name (guint32 i)
352 g_assert (i < G_N_ELEMENTS (interp_opflags_names));
353 return interp_opflags_names [i];
356 static char*
357 interp_opt_descr (guint32 flags)
359 GString *str = g_string_new ("");
360 int i;
361 gboolean need_comma;
363 need_comma = FALSE;
364 for (i = 0; i < G_N_ELEMENTS (interp_opflags_names); ++i) {
365 if (flags & (1 << i) && interp_optflag_get_name (i)) {
366 if (need_comma)
367 g_string_append_c (str, ',');
368 g_string_append (str, interp_optflag_get_name (i));
369 need_comma = TRUE;
372 return g_string_free (str, FALSE);
375 typedef int (*TestMethod) (void);
377 #if 0
378 static void
379 domain_dump_native_code (MonoDomain *domain) {
380 // need to poke into the domain, move to metadata/domain.c
381 // need to empty jit_info_table and code_mp
383 #endif
385 static gboolean do_regression_retries;
386 static int regression_test_skip_index;
389 static gboolean
390 method_should_be_regression_tested (MonoMethod *method, gboolean interp)
392 ERROR_DECL (error);
394 if (strncmp (method->name, "test_", 5) != 0)
395 return FALSE;
397 static gboolean filter_method_init = FALSE;
398 static const char *filter_method = NULL;
400 if (!filter_method_init) {
401 filter_method = g_getenv ("REGRESSION_FILTER_METHOD");
402 filter_method_init = TRUE;
405 if (filter_method) {
406 const char *name = filter_method;
408 if ((strchr (name, '.') > name) || strchr (name, ':')) {
409 MonoMethodDesc *desc = mono_method_desc_new (name, TRUE);
410 gboolean res = mono_method_desc_full_match (desc, method);
411 mono_method_desc_free (desc);
412 return res;
413 } else {
414 return strcmp (method->name, name) == 0;
418 MonoCustomAttrInfo* ainfo = mono_custom_attrs_from_method_checked (method, error);
419 mono_error_cleanup (error);
420 if (!ainfo)
421 return TRUE;
423 int j;
424 for (j = 0; j < ainfo->num_attrs; ++j) {
425 MonoCustomAttrEntry *centry = &ainfo->attrs [j];
426 if (centry->ctor == NULL)
427 continue;
429 MonoClass *klass = centry->ctor->klass;
430 if (strcmp (m_class_get_name (klass), "CategoryAttribute") || mono_method_signature_internal (centry->ctor)->param_count != 1)
431 continue;
433 gpointer *typed_args, *named_args;
434 int num_named_args;
435 CattrNamedArg *arginfo;
437 mono_reflection_create_custom_attr_data_args_noalloc (
438 mono_defaults.corlib, centry->ctor, centry->data, centry->data_size,
439 &typed_args, &named_args, &num_named_args, &arginfo, error);
440 if (!is_ok (error))
441 continue;
443 char *utf8_str = (char*)(void*)typed_args[0]; //this points into image memory that is constant
444 g_free (typed_args);
445 g_free (named_args);
446 g_free (arginfo);
448 if (interp && !strcmp (utf8_str, "!INTERPRETER")) {
449 g_print ("skip %s...\n", method->name);
450 return FALSE;
453 #if HOST_WASM
454 if (!strcmp (utf8_str, "!WASM")) {
455 g_print ("skip %s...\n", method->name);
456 return FALSE;
458 #endif
459 if (mono_aot_mode == MONO_AOT_MODE_FULL && !strcmp (utf8_str, "!FULLAOT")) {
460 g_print ("skip %s...\n", method->name);
461 return FALSE;
464 if ((mono_aot_mode == MONO_AOT_MODE_INTERP_LLVMONLY || mono_aot_mode == MONO_AOT_MODE_LLVMONLY) && !strcmp (utf8_str, "!BITCODE")) {
465 g_print ("skip %s...\n", method->name);
466 return FALSE;
470 return TRUE;
473 static void
474 mini_regression_step (MonoImage *image, int verbose, int *total_run, int *total,
475 guint32 opt_flags,
476 GTimer *timer, MonoDomain *domain)
478 int result, expected, failed, cfailed, run, code_size;
479 double elapsed, comp_time, start_time;
480 char *n;
481 int i;
483 mono_set_defaults (verbose, opt_flags);
484 n = mono_opt_descr (opt_flags);
485 g_print ("Test run: image=%s, opts=%s\n", mono_image_get_filename (image), n);
486 g_free (n);
487 cfailed = failed = run = code_size = 0;
488 comp_time = elapsed = 0.0;
489 int local_skip_index = 0;
491 /* fixme: ugly hack - delete all previously compiled methods */
492 if (domain_jit_info (domain)) {
493 g_hash_table_destroy (domain_jit_info (domain)->jit_trampoline_hash);
494 domain_jit_info (domain)->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
495 mono_internal_hash_table_destroy (&(domain->jit_code_hash));
496 mono_jit_code_hash_init (&(domain->jit_code_hash));
499 g_timer_start (timer);
500 if (mini_stats_fd)
501 fprintf (mini_stats_fd, "[");
502 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
503 ERROR_DECL (error);
504 MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
505 if (!method) {
506 mono_error_cleanup (error); /* FIXME don't swallow the error */
507 continue;
509 if (method_should_be_regression_tested (method, FALSE)) {
510 MonoCompile *cfg = NULL;
511 TestMethod func = NULL;
513 expected = atoi (method->name + 5);
514 run++;
515 start_time = g_timer_elapsed (timer, NULL);
517 #ifdef DISABLE_JIT
518 #ifdef MONO_USE_AOT_COMPILER
519 ERROR_DECL (error);
520 func = (TestMethod)mono_aot_get_method (mono_get_root_domain (), method, error);
521 mono_error_cleanup (error);
522 #else
523 g_error ("No JIT or AOT available, regression testing not possible!")
524 #endif
526 #else
527 comp_time -= start_time;
528 cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, opt_flags), mono_get_root_domain (), JIT_FLAG_RUN_CCTORS, 0, -1);
529 comp_time += g_timer_elapsed (timer, NULL);
530 if (cfg->exception_type == MONO_EXCEPTION_NONE) {
531 #ifdef MONO_USE_AOT_COMPILER
532 ERROR_DECL (error);
533 func = (TestMethod)mono_aot_get_method (mono_get_root_domain (), method, error);
534 mono_error_cleanup (error);
535 if (!func)
536 func = (TestMethod)(gpointer)cfg->native_code;
537 #else
538 func = (TestMethod)(gpointer)cfg->native_code;
539 #endif
540 func = (TestMethod)mono_create_ftnptr (mono_get_root_domain (), (gpointer)func);
542 #endif
544 if (func) {
545 if (do_regression_retries) {
546 ++local_skip_index;
548 if(local_skip_index <= regression_test_skip_index)
549 continue;
550 ++regression_test_skip_index;
553 if (verbose >= 2)
554 g_print ("Running '%s' ...\n", method->name);
556 #if HOST_WASM
557 //WASM AOT injects dummy args and we must call with exact signatures
558 int (*func_2)(int) = (int (*)(int))(void*)func;
559 result = func_2 (-1);
560 #else
561 result = func ();
562 #endif
563 if (result != expected) {
564 failed++;
565 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
567 if (cfg) {
568 code_size += cfg->code_len;
569 mono_destroy_compile (cfg);
571 } else {
572 cfailed++;
573 g_print ("Test '%s' failed compilation.\n", method->name);
575 if (mini_stats_fd)
576 fprintf (mini_stats_fd, "%f, ",
577 g_timer_elapsed (timer, NULL) - start_time);
580 if (mini_stats_fd)
581 fprintf (mini_stats_fd, "],\n");
582 g_timer_stop (timer);
583 elapsed = g_timer_elapsed (timer, NULL);
584 if (failed > 0 || cfailed > 0){
585 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n",
586 run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
587 } else {
588 g_print ("Results: total tests: %d, all pass \n", run);
591 g_print ("Elapsed time: %f secs (%f, %f), Code size: %d\n\n", elapsed,
592 elapsed - comp_time, comp_time, code_size);
593 *total += failed + cfailed;
594 *total_run += run;
597 static int
598 mini_regression (MonoImage *image, int verbose, int *total_run)
600 guint32 i, opt;
601 MonoMethod *method;
602 char *n;
603 GTimer *timer = g_timer_new ();
604 MonoDomain *domain = mono_domain_get ();
605 guint32 exclude = 0;
606 int total;
608 /* Note: mono_hwcap_init () called in mono_init () before we get here. */
609 mono_arch_cpu_optimizations (&exclude);
611 if (mini_stats_fd) {
612 fprintf (mini_stats_fd, "$stattitle = \'Mono Benchmark Results (various optimizations)\';\n");
614 fprintf (mini_stats_fd, "$graph->set_legend(qw(");
615 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); opt++) {
616 guint32 opt_flags = opt_sets [opt];
617 n = mono_opt_descr (opt_flags);
618 if (!n [0])
619 n = (char *)"none";
620 if (opt)
621 fprintf (mini_stats_fd, " ");
622 fprintf (mini_stats_fd, "%s", n);
626 fprintf (mini_stats_fd, "));\n");
628 fprintf (mini_stats_fd, "@data = (\n");
629 fprintf (mini_stats_fd, "[");
632 /* load the metadata */
633 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
634 ERROR_DECL (error);
635 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
636 if (!method) {
637 mono_error_cleanup (error);
638 continue;
640 mono_class_init_internal (method->klass);
642 if (!strncmp (method->name, "test_", 5) && mini_stats_fd) {
643 fprintf (mini_stats_fd, "\"%s\",", method->name);
646 if (mini_stats_fd)
647 fprintf (mini_stats_fd, "],\n");
650 total = 0;
651 *total_run = 0;
652 if (mono_do_single_method_regression) {
653 GSList *iter;
655 mini_regression_step (image, verbose, total_run, &total,
657 timer, domain);
658 if (total)
659 return total;
660 g_print ("Single method regression: %d methods\n", g_slist_length (mono_single_method_list));
662 for (iter = mono_single_method_list; iter; iter = g_slist_next (iter)) {
663 char *method_name;
665 mono_current_single_method = (MonoMethod *)iter->data;
667 method_name = mono_method_full_name (mono_current_single_method, TRUE);
668 g_print ("Current single method: %s\n", method_name);
669 g_free (method_name);
671 mini_regression_step (image, verbose, total_run, &total,
673 timer, domain);
674 if (total)
675 return total;
677 } else {
678 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); ++opt) {
679 /* builtin-types.cs & aot-tests.cs need OPT_INTRINS enabled */
680 if (!strcmp ("builtin-types", image->assembly_name) || !strcmp ("aot-tests", image->assembly_name))
681 if (!(opt_sets [opt] & MONO_OPT_INTRINS))
682 continue;
684 //we running in AOT only, it makes no sense to try multiple flags
685 if ((mono_aot_mode == MONO_AOT_MODE_FULL || mono_aot_mode == MONO_AOT_MODE_LLVMONLY) && opt_sets [opt] != DEFAULT_OPTIMIZATIONS) {
686 continue;
689 mini_regression_step (image, verbose, total_run, &total,
690 opt_sets [opt] & ~exclude,
691 timer, domain);
695 if (mini_stats_fd) {
696 fprintf (mini_stats_fd, ");\n");
697 fflush (mini_stats_fd);
700 g_timer_destroy (timer);
701 return total;
704 static int
705 mini_regression_list (int verbose, int count, char *images [])
707 int i, total, total_run, run;
708 MonoAssembly *ass;
710 total_run = total = 0;
711 for (i = 0; i < count; ++i) {
712 MonoAssemblyOpenRequest req;
713 mono_assembly_request_prepare_open (&req, MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_get_root_domain ()));
714 ass = mono_assembly_request_open (images [i], &req, NULL);
715 if (!ass) {
716 g_warning ("failed to load assembly: %s", images [i]);
717 continue;
719 total += mini_regression (mono_assembly_get_image_internal (ass), verbose, &run);
720 total_run += run;
722 if (total > 0){
723 g_print ("Overall results: tests: %d, failed: %d, opt combinations: %d (pass: %.2f%%)\n",
724 total_run, total, (int)G_N_ELEMENTS (opt_sets), 100.0*(total_run-total)/total_run);
725 } else {
726 g_print ("Overall results: tests: %d, 100%% pass, opt combinations: %d\n",
727 total_run, (int)G_N_ELEMENTS (opt_sets));
730 return total;
733 static void
734 interp_regression_step (MonoImage *image, int verbose, int *total_run, int *total, const guint32 *opt_flags, GTimer *timer, MonoDomain *domain)
736 int result, expected, failed, cfailed, run;
737 double elapsed, transform_time;
738 int i;
739 MonoObject *result_obj;
740 int local_skip_index = 0;
742 const char *n = NULL;
743 if (opt_flags) {
744 mini_get_interp_callbacks ()->set_optimizations (*opt_flags);
745 n = interp_opt_descr (*opt_flags);
746 } else {
747 n = mono_interp_opts_string;
749 g_print ("Test run: image=%s, opts=%s\n", mono_image_get_filename (image), n);
751 cfailed = failed = run = 0;
752 transform_time = elapsed = 0.0;
754 mini_get_interp_callbacks ()->invalidate_transformed (domain);
756 g_timer_start (timer);
757 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
758 ERROR_DECL (error);
759 MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
760 if (!method) {
761 mono_error_cleanup (error); /* FIXME don't swallow the error */
762 continue;
765 if (method_should_be_regression_tested (method, TRUE)) {
766 ERROR_DECL (interp_error);
767 MonoObject *exc = NULL;
769 if (do_regression_retries) {
770 ++local_skip_index;
772 if(local_skip_index <= regression_test_skip_index)
773 continue;
774 ++regression_test_skip_index;
777 result_obj = mini_get_interp_callbacks ()->runtime_invoke (method, NULL, NULL, &exc, interp_error);
778 if (!is_ok (interp_error)) {
779 cfailed++;
780 g_print ("Test '%s' execution failed.\n", method->name);
781 } else if (exc != NULL) {
782 g_print ("Exception in Test '%s' occurred:\n", method->name);
783 mono_object_describe (exc);
784 run++;
785 failed++;
786 } else {
787 result = *(gint32 *) mono_object_unbox_internal (result_obj);
788 expected = atoi (method->name + 5); // FIXME: oh no.
789 run++;
791 if (result != expected) {
792 failed++;
793 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
798 g_timer_stop (timer);
799 elapsed = g_timer_elapsed (timer, NULL);
800 if (failed > 0 || cfailed > 0){
801 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n",
802 run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
803 } else {
804 g_print ("Results: total tests: %d, all pass \n", run);
807 g_print ("Elapsed time: %f secs (%f, %f)\n\n", elapsed,
808 elapsed - transform_time, transform_time);
809 *total += failed + cfailed;
810 *total_run += run;
813 static int
814 interp_regression (MonoImage *image, int verbose, int *total_run)
816 MonoMethod *method;
817 GTimer *timer = g_timer_new ();
818 MonoDomain *domain = mono_domain_get ();
819 guint32 i;
820 int total;
822 /* load the metadata */
823 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
824 ERROR_DECL (error);
825 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
826 if (!method) {
827 mono_error_cleanup (error);
828 continue;
830 mono_class_init_internal (method->klass);
833 total = 0;
834 *total_run = 0;
836 if (mono_interp_opts_string) {
837 /* explicit option requested*/
838 interp_regression_step (image, verbose, total_run, &total, NULL, timer, domain);
839 } else {
840 for (int opt = 0; opt < G_N_ELEMENTS (interp_opt_sets); ++opt)
841 interp_regression_step (image, verbose, total_run, &total, &interp_opt_sets [opt], timer, domain);
844 g_timer_destroy (timer);
845 return total;
848 /* TODO: merge this code with the regression harness of the JIT */
849 static int
850 mono_interp_regression_list (int verbose, int count, char *images [])
852 int i, total, total_run, run;
854 total_run = total = 0;
855 for (i = 0; i < count; ++i) {
856 MonoAssemblyOpenRequest req;
857 mono_assembly_request_prepare_open (&req, MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_get_root_domain ()));
858 MonoAssembly *ass = mono_assembly_request_open (images [i], &req, NULL);
859 if (!ass) {
860 g_warning ("failed to load assembly: %s", images [i]);
861 continue;
863 total += interp_regression (mono_assembly_get_image_internal (ass), verbose, &run);
864 total_run += run;
866 if (total > 0) {
867 g_print ("Overall results: tests: %d, failed: %d (pass: %.2f%%)\n", total_run, total, 100.0*(total_run-total)/total_run);
868 } else {
869 g_print ("Overall results: tests: %d, 100%% pass\n", total_run);
872 return total;
876 #ifdef MONO_JIT_INFO_TABLE_TEST
877 typedef struct _JitInfoData
879 guint start;
880 guint length;
881 MonoJitInfo *ji;
882 struct _JitInfoData *next;
883 } JitInfoData;
885 typedef struct
887 guint start;
888 guint length;
889 int num_datas;
890 JitInfoData *data;
891 } Region;
893 typedef struct
895 int num_datas;
896 int num_regions;
897 Region *regions;
898 int num_frees;
899 JitInfoData *frees;
900 } ThreadData;
902 static int num_threads;
903 static ThreadData *thread_datas;
904 static MonoDomain *test_domain;
906 static JitInfoData*
907 alloc_random_data (Region *region)
909 JitInfoData **data;
910 JitInfoData *prev;
911 guint prev_end;
912 guint next_start;
913 guint max_len;
914 JitInfoData *d;
915 int num_retries = 0;
916 int pos, i;
918 restart:
919 prev = NULL;
920 data = &region->data;
921 pos = random () % (region->num_datas + 1);
922 i = 0;
923 while (*data != NULL) {
924 if (i++ == pos)
925 break;
926 prev = *data;
927 data = &(*data)->next;
930 if (prev == NULL)
931 g_assert (*data == region->data);
932 else
933 g_assert (prev->next == *data);
935 if (prev == NULL)
936 prev_end = region->start;
937 else
938 prev_end = prev->start + prev->length;
940 if (*data == NULL)
941 next_start = region->start + region->length;
942 else
943 next_start = (*data)->start;
945 g_assert (prev_end <= next_start);
947 max_len = next_start - prev_end;
948 if (max_len < 128) {
949 if (++num_retries >= 10)
950 return NULL;
951 goto restart;
953 if (max_len > 1024)
954 max_len = 1024;
956 d = g_new0 (JitInfoData, 1);
957 d->start = prev_end + random () % (max_len / 2);
958 d->length = random () % MIN (max_len, next_start - d->start) + 1;
960 g_assert (d->start >= prev_end && d->start + d->length <= next_start);
962 d->ji = g_new0 (MonoJitInfo, 1);
963 d->ji->d.method = (MonoMethod*) 0xABadBabe;
964 d->ji->code_start = (gpointer)(gulong) d->start;
965 d->ji->code_size = d->length;
966 d->ji->cas_inited = 1; /* marks an allocated jit info */
968 d->next = *data;
969 *data = d;
971 ++region->num_datas;
973 return d;
976 static JitInfoData**
977 choose_random_data (Region *region)
979 int n;
980 int i;
981 JitInfoData **d;
983 g_assert (region->num_datas > 0);
985 n = random () % region->num_datas;
987 for (d = &region->data, i = 0;
988 i < n;
989 d = &(*d)->next, ++i)
992 return d;
995 static Region*
996 choose_random_region (ThreadData *td)
998 return &td->regions [random () % td->num_regions];
1001 static ThreadData*
1002 choose_random_thread (void)
1004 return &thread_datas [random () % num_threads];
1007 static void
1008 free_jit_info_data (ThreadData *td, JitInfoData *free)
1010 free->next = td->frees;
1011 td->frees = free;
1013 if (++td->num_frees >= 1000) {
1014 int i;
1016 for (i = 0; i < 500; ++i)
1017 free = free->next;
1019 while (free->next != NULL) {
1020 JitInfoData *next = free->next->next;
1022 //g_free (free->next->ji);
1023 g_free (free->next);
1024 free->next = next;
1026 --td->num_frees;
1031 #define NUM_THREADS 8
1032 #define REGIONS_PER_THREAD 10
1033 #define REGION_SIZE 0x10000
1035 #define MAX_ADDR (REGION_SIZE * REGIONS_PER_THREAD * NUM_THREADS)
1037 #define MODE_ALLOC 1
1038 #define MODE_FREE 2
1040 static void
1041 test_thread_func (gpointer void_arg)
1043 ThreadData* td = (ThreadData*)void_arg;
1044 int mode = MODE_ALLOC;
1045 int i = 0;
1046 gulong lookup_successes = 0, lookup_failures = 0;
1047 MonoDomain *domain = test_domain;
1048 int thread_num = (int)(td - thread_datas);
1049 gboolean modify_thread = thread_num < NUM_THREADS / 2; /* only half of the threads modify the table */
1051 for (;;) {
1052 int alloc;
1053 int lookup = 1;
1055 if (td->num_datas == 0) {
1056 lookup = 0;
1057 alloc = 1;
1058 } else if (modify_thread && random () % 1000 < 5) {
1059 lookup = 0;
1060 if (mode == MODE_ALLOC)
1061 alloc = (random () % 100) < 70;
1062 else if (mode == MODE_FREE)
1063 alloc = (random () % 100) < 30;
1066 if (lookup) {
1067 /* modify threads sometimes look up their own jit infos */
1068 if (modify_thread && random () % 10 < 5) {
1069 Region *region = choose_random_region (td);
1071 if (region->num_datas > 0) {
1072 JitInfoData **data = choose_random_data (region);
1073 guint pos = (*data)->start + random () % (*data)->length;
1074 MonoJitInfo *ji;
1076 ji = mono_jit_info_table_find (domain, (char*)(gsize)pos);
1078 g_assert (ji->cas_inited);
1079 g_assert ((*data)->ji == ji);
1081 } else {
1082 int pos = random () % MAX_ADDR;
1083 char *addr = (char*)(uintptr_t)pos;
1084 MonoJitInfo *ji;
1086 ji = mono_jit_info_table_find (domain, addr);
1089 * FIXME: We are actually not allowed
1090 * to do this. By the time we examine
1091 * the ji another thread might already
1092 * have removed it.
1094 if (ji != NULL) {
1095 g_assert (addr >= (char*)ji->code_start && addr < (char*)ji->code_start + ji->code_size);
1096 ++lookup_successes;
1097 } else
1098 ++lookup_failures;
1100 } else if (alloc) {
1101 JitInfoData *data = alloc_random_data (choose_random_region (td));
1103 if (data != NULL) {
1104 mono_jit_info_table_add (domain, data->ji);
1106 ++td->num_datas;
1108 } else {
1109 Region *region = choose_random_region (td);
1111 if (region->num_datas > 0) {
1112 JitInfoData **data = choose_random_data (region);
1113 JitInfoData *free;
1115 mono_jit_info_table_remove (domain, (*data)->ji);
1117 //(*data)->ji->cas_inited = 0; /* marks a free jit info */
1119 free = *data;
1120 *data = (*data)->next;
1122 free_jit_info_data (td, free);
1124 --region->num_datas;
1125 --td->num_datas;
1129 if (++i % 100000 == 0) {
1130 int j;
1131 g_print ("num datas %d (%ld - %ld): %d", (int)(td - thread_datas),
1132 lookup_successes, lookup_failures, td->num_datas);
1133 for (j = 0; j < td->num_regions; ++j)
1134 g_print (" %d", td->regions [j].num_datas);
1135 g_print ("\n");
1138 if (td->num_datas < 100)
1139 mode = MODE_ALLOC;
1140 else if (td->num_datas > 2000)
1141 mode = MODE_FREE;
1146 static void
1147 small_id_thread_func (gpointer arg)
1149 MonoThread *thread = mono_thread_current ();
1150 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1152 g_print ("my small id is %d\n", (int)thread->small_id);
1153 mono_hazard_pointer_clear (hp, 1);
1154 sleep (3);
1155 g_print ("done %d\n", (int)thread->small_id);
1159 static void
1160 jit_info_table_test (MonoDomain *domain)
1162 ERROR_DECL (error);
1163 int i;
1165 g_print ("testing jit_info_table\n");
1167 num_threads = NUM_THREADS;
1168 thread_datas = g_new0 (ThreadData, num_threads);
1170 for (i = 0; i < num_threads; ++i) {
1171 int j;
1173 thread_datas [i].num_regions = REGIONS_PER_THREAD;
1174 thread_datas [i].regions = g_new0 (Region, REGIONS_PER_THREAD);
1176 for (j = 0; j < REGIONS_PER_THREAD; ++j) {
1177 thread_datas [i].regions [j].start = (num_threads * j + i) * REGION_SIZE;
1178 thread_datas [i].regions [j].length = REGION_SIZE;
1182 test_domain = domain;
1185 for (i = 0; i < 72; ++i)
1186 mono_thread_create (domain, small_id_thread_func, NULL);
1188 sleep (2);
1191 for (i = 0; i < num_threads; ++i) {
1192 mono_thread_create_checked (domain, (gpointer)test_thread_func, &thread_datas [i], error);
1193 mono_error_assert_ok (error);
1196 #endif
1198 enum {
1199 DO_BENCH,
1200 DO_REGRESSION,
1201 DO_SINGLE_METHOD_REGRESSION,
1202 DO_COMPILE,
1203 DO_EXEC,
1204 DO_DRAW,
1205 DO_DEBUGGER
1208 typedef struct CompileAllThreadArgs {
1209 MonoAssembly *ass;
1210 int verbose;
1211 guint32 opts;
1212 guint32 recompilation_times;
1213 } CompileAllThreadArgs;
1215 static void
1216 compile_all_methods_thread_main_inner (CompileAllThreadArgs *args)
1218 MonoAssembly *ass = args->ass;
1219 int verbose = args->verbose;
1220 MonoImage *image = mono_assembly_get_image_internal (ass);
1221 MonoMethod *method;
1222 MonoCompile *cfg;
1223 int i, count = 0, fail_count = 0;
1225 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
1226 ERROR_DECL (error);
1227 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1228 MonoMethodSignature *sig;
1230 if (mono_metadata_has_generic_params (image, token))
1231 continue;
1233 method = mono_get_method_checked (image, token, NULL, NULL, error);
1234 if (!method) {
1235 mono_error_cleanup (error); /* FIXME don't swallow the error */
1236 continue;
1238 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1239 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1240 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1241 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1242 continue;
1244 if (mono_class_is_gtd (method->klass))
1245 continue;
1246 sig = mono_method_signature_internal (method);
1247 if (!sig) {
1248 char * desc = mono_method_full_name (method, TRUE);
1249 g_print ("Could not retrieve method signature for %s\n", desc);
1250 g_free (desc);
1251 fail_count ++;
1252 continue;
1255 if (sig->has_type_parameters)
1256 continue;
1258 count++;
1259 if (verbose) {
1260 char * desc = mono_method_full_name (method, TRUE);
1261 g_print ("Compiling %d %s\n", count, desc);
1262 g_free (desc);
1264 if (mono_use_interpreter) {
1265 mini_get_interp_callbacks ()->create_method_pointer (method, TRUE, error);
1266 // FIXME There are a few failures due to DllNotFoundException related to System.Native
1267 if (verbose && !is_ok (error))
1268 g_print ("Compilation of %s failed\n", mono_method_full_name (method, TRUE));
1269 } else {
1270 cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, args->opts), mono_get_root_domain (), (JitFlags)JIT_FLAG_DISCARD_RESULTS, 0, -1);
1271 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
1272 const char *msg = cfg->exception_message;
1273 if (cfg->exception_type == MONO_EXCEPTION_MONO_ERROR)
1274 msg = mono_error_get_message (cfg->error);
1275 g_print ("Compilation of %s failed with exception '%s':\n", mono_method_full_name (cfg->method, TRUE), msg);
1276 fail_count ++;
1278 mono_destroy_compile (cfg);
1282 if (fail_count)
1283 exit (1);
1286 static void
1287 compile_all_methods_thread_main (gpointer void_args)
1289 CompileAllThreadArgs *args = (CompileAllThreadArgs*)void_args;
1290 guint32 i;
1291 for (i = 0; i < args->recompilation_times; ++i)
1292 compile_all_methods_thread_main_inner (args);
1295 static void
1296 compile_all_methods (MonoAssembly *ass, int verbose, guint32 opts, guint32 recompilation_times)
1298 ERROR_DECL (error);
1299 CompileAllThreadArgs args;
1301 args.ass = ass;
1302 args.verbose = verbose;
1303 args.opts = opts;
1304 args.recompilation_times = recompilation_times;
1307 * Need to create a mono thread since compilation might trigger
1308 * running of managed code.
1310 mono_thread_create_checked (mono_domain_get (), (gpointer)compile_all_methods_thread_main, &args, error);
1311 mono_error_assert_ok (error);
1313 mono_thread_manage_internal ();
1317 * mono_jit_exec:
1318 * \param assembly reference to an assembly
1319 * \param argc argument count
1320 * \param argv argument vector
1321 * Start execution of a program.
1323 int
1324 mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
1326 int rv;
1327 MONO_ENTER_GC_UNSAFE;
1328 rv = mono_jit_exec_internal (domain, assembly, argc, argv);
1329 MONO_EXIT_GC_UNSAFE;
1330 return rv;
1334 mono_jit_exec_internal (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
1336 MONO_REQ_GC_UNSAFE_MODE;
1337 ERROR_DECL (error);
1338 MonoImage *image = mono_assembly_get_image_internal (assembly);
1340 // We need to ensure that any module cctor for this image
1341 // is run *before* we invoke the entry point
1342 // For more information, see https://blogs.msdn.microsoft.com/junfeng/2005/11/19/module-initializer-a-k-a-module-constructor/
1344 // This is required in order for tools like Costura
1345 // (https://github.com/Fody/Costura) to work properly, as they inject
1346 // a module initializer which sets up event handlers (e.g. AssemblyResolve)
1347 // that allow the main method to run properly
1348 if (!mono_runtime_run_module_cctor(image, domain, error)) {
1349 g_print ("Failed to run module constructor due to %s\n", mono_error_get_message (error));
1350 return 1;
1353 MonoMethod *method;
1354 guint32 entry = mono_image_get_entry_point (image);
1356 if (!entry) {
1357 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
1358 /* FIXME: remove this silly requirement. */
1359 mono_environment_exitcode_set (1);
1360 return 1;
1363 method = mono_get_method_checked (image, entry, NULL, NULL, error);
1364 if (method == NULL){
1365 g_print ("The entry point method could not be loaded due to %s\n", mono_error_get_message (error));
1366 mono_error_cleanup (error);
1367 mono_environment_exitcode_set (1);
1368 return 1;
1371 if (mono_llvm_only) {
1372 MonoObject *exc = NULL;
1373 int res;
1375 res = mono_runtime_try_run_main (method, argc, argv, &exc);
1376 if (exc) {
1377 mono_unhandled_exception_internal (exc);
1378 mono_invoke_unhandled_exception_hook (exc);
1379 g_assert_not_reached ();
1381 return res;
1382 } else {
1383 int res = mono_runtime_run_main_checked (method, argc, argv, error);
1384 if (!is_ok (error)) {
1385 MonoException *ex = mono_error_convert_to_exception (error);
1386 if (ex) {
1387 mono_unhandled_exception_internal (&ex->object);
1388 mono_invoke_unhandled_exception_hook (&ex->object);
1389 g_assert_not_reached ();
1392 return res;
1396 typedef struct
1398 MonoDomain *domain;
1399 const char *file;
1400 int argc;
1401 char **argv;
1402 guint32 opts;
1403 char *aot_options;
1404 } MainThreadArgs;
1406 static void main_thread_handler (gpointer user_data)
1408 MainThreadArgs *main_args = (MainThreadArgs *)user_data;
1409 MonoAssembly *assembly;
1411 if (mono_compile_aot) {
1412 int i, res;
1413 gpointer *aot_state = NULL;
1415 /* Treat the other arguments as assemblies to compile too */
1416 for (i = 0; i < main_args->argc; ++i) {
1417 assembly = mono_domain_assembly_open_internal (main_args->domain, mono_domain_default_alc (main_args->domain), main_args->argv [i]);
1418 if (!assembly) {
1419 if (mono_is_problematic_file (main_args->argv [i])) {
1420 fprintf (stderr, "Info: AOT of problematic assembly %s skipped. This is expected.\n", main_args->argv [i]);
1421 continue;
1422 } else {
1423 fprintf (stderr, "Can not open image %s\n", main_args->argv [i]);
1424 exit (1);
1427 /* Check that the assembly loaded matches the filename */
1429 MonoImageOpenStatus status;
1430 MonoImage *img;
1432 img = mono_image_open (main_args->argv [i], &status);
1433 if (img && strcmp (img->name, assembly->image->name)) {
1434 fprintf (stderr, "Error: Loaded assembly '%s' doesn't match original file name '%s'. Set MONO_PATH to the assembly's location.\n", assembly->image->name, img->name);
1435 exit (1);
1438 res = mono_compile_assembly (assembly, main_args->opts, main_args->aot_options, &aot_state);
1439 if (res != 0) {
1440 fprintf (stderr, "AOT of image %s failed.\n", main_args->argv [i]);
1441 exit (1);
1444 if (aot_state) {
1445 res = mono_compile_deferred_assemblies (main_args->opts, main_args->aot_options, &aot_state);
1446 if (res != 0) {
1447 fprintf (stderr, "AOT of mode-specific deferred assemblies failed.\n");
1448 exit (1);
1451 } else {
1452 assembly = mono_domain_assembly_open_internal (main_args->domain, mono_domain_default_alc (main_args->domain), main_args->file);
1453 if (!assembly){
1454 fprintf (stderr, "Can not open image %s\n", main_args->file);
1455 exit (1);
1459 * This must be done in a thread managed by mono since it can invoke
1460 * managed code.
1462 if (main_args->opts & MONO_OPT_PRECOMP)
1463 mono_precompile_assemblies ();
1465 mono_jit_exec (main_args->domain, assembly, main_args->argc, main_args->argv);
1469 static int
1470 load_agent (MonoDomain *domain, char *desc)
1472 ERROR_DECL (error);
1473 char* col = strchr (desc, ':');
1474 char *agent, *args;
1475 MonoAssembly *agent_assembly;
1476 MonoImage *image;
1477 MonoMethod *method;
1478 guint32 entry;
1479 MonoArray *main_args;
1480 gpointer pa [1];
1481 MonoImageOpenStatus open_status;
1483 if (col) {
1484 agent = (char *)g_memdup (desc, col - desc + 1);
1485 agent [col - desc] = '\0';
1486 args = col + 1;
1487 } else {
1488 agent = g_strdup (desc);
1489 args = NULL;
1492 MonoAssemblyOpenRequest req;
1493 mono_assembly_request_prepare_open (&req, MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_get_root_domain ()));
1494 agent_assembly = mono_assembly_request_open (agent, &req, &open_status);
1495 if (!agent_assembly) {
1496 fprintf (stderr, "Cannot open agent assembly '%s': %s.\n", agent, mono_image_strerror (open_status));
1497 g_free (agent);
1498 return 2;
1502 * Can't use mono_jit_exec (), as it sets things which might confuse the
1503 * real Main method.
1505 image = mono_assembly_get_image_internal (agent_assembly);
1506 entry = mono_image_get_entry_point (image);
1507 if (!entry) {
1508 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
1509 g_free (agent);
1510 return 1;
1513 method = mono_get_method_checked (image, entry, NULL, NULL, error);
1514 if (method == NULL){
1515 g_print ("The entry point method of assembly '%s' could not be loaded due to %s\n", agent, mono_error_get_message (error));
1516 mono_error_cleanup (error);
1517 g_free (agent);
1518 return 1;
1521 mono_thread_set_main (mono_thread_current ());
1523 if (args) {
1524 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 1, error);
1525 if (main_args) {
1526 MonoString *str = mono_string_new_checked (domain, args, error);
1527 if (str)
1528 mono_array_set_internal (main_args, MonoString*, 0, str);
1530 } else {
1531 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 0, error);
1533 if (!main_args) {
1534 g_print ("Could not allocate array for main args of assembly '%s' due to %s\n", agent, mono_error_get_message (error));
1535 mono_error_cleanup (error);
1536 g_free (agent);
1537 return 1;
1541 pa [0] = main_args;
1542 /* Pass NULL as 'exc' so unhandled exceptions abort the runtime */
1543 mono_runtime_invoke_checked (method, NULL, pa, error);
1544 if (!is_ok (error)) {
1545 g_print ("The entry point method of assembly '%s' could not execute due to %s\n", agent, mono_error_get_message (error));
1546 mono_error_cleanup (error);
1547 g_free (agent);
1548 return 1;
1551 g_free (agent);
1552 return 0;
1555 static void
1556 mini_usage_jitdeveloper (void)
1558 int i;
1560 fprintf (stdout,
1561 "Runtime and JIT debugging options:\n"
1562 " --apply-bindings=FILE Apply assembly bindings from FILE (only for AOT)\n"
1563 " --breakonex Inserts a breakpoint on exceptions\n"
1564 " --break METHOD Inserts a breakpoint at METHOD entry\n"
1565 " --break-at-bb METHOD N Inserts a breakpoint in METHOD at BB N\n"
1566 " --compile METHOD Just compile METHOD in assembly\n"
1567 " --compile-all=N Compiles all the methods in the assembly multiple times (default: 1)\n"
1568 " --ncompile N Number of times to compile METHOD (default: 1)\n"
1569 " --print-vtable Print the vtable of all used classes\n"
1570 " --regression Runs the regression test contained in the assembly\n"
1571 " --single-method=OPTS Runs regressions with only one method optimized with OPTS at any time\n"
1572 " --statfile FILE Sets the stat file to FILE\n"
1573 " --stats Print statistics about the JIT operations\n"
1574 " --inject-async-exc METHOD OFFSET Inject an asynchronous exception at METHOD\n"
1575 " --verify-all Run the verifier on all assemblies and methods\n"
1576 " --full-aot Avoid JITting any code\n"
1577 " --llvmonly Use LLVM compiled code only\n"
1578 " --agent=ASSEMBLY[:ARG] Loads the specific agent assembly and executes its Main method with the given argument before loading the main assembly.\n"
1579 " --no-x86-stack-align Don't align stack on x86\n"
1580 "\n"
1581 "The options supported by MONO_DEBUG can also be passed on the command line.\n"
1582 "\n"
1583 "Other options:\n"
1584 " --graph[=TYPE] METHOD Draws a graph of the specified method:\n");
1586 for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
1587 fprintf (stdout, " %-10s %s\n", graph_names [i].name, graph_names [i].desc);
1591 static void
1592 mini_usage_list_opt (void)
1594 int i;
1596 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i)
1597 fprintf (stdout, " %-10s %s\n", optflag_get_name (i), optflag_get_desc (i));
1600 static void
1601 mini_usage (void)
1603 fprintf (stdout,
1604 "Usage is: mono [options] program [program-options]\n"
1605 "\n"
1606 "Development:\n"
1607 " --aot[=<options>] Compiles the assembly to native code\n"
1608 " --debug[=<options>] Enable debugging support, use --help-debug for details\n"
1609 " --debugger-agent=options Enable the debugger agent\n"
1610 " --profile[=profiler] Runs in profiling mode with the specified profiler module\n"
1611 " --trace[=EXPR] Enable tracing, use --help-trace for details\n"
1612 " --jitmap Output a jit method map to /tmp/perf-PID.map\n"
1613 " --help-devel Shows more options available to developers\n"
1614 "\n"
1615 "Runtime:\n"
1616 " --config FILE Loads FILE as the Mono config\n"
1617 " --verbose, -v Increases the verbosity level\n"
1618 " --help, -h Show usage information\n"
1619 " --version, -V Show version information\n"
1620 " --version=number Show version number\n"
1621 " --runtime=VERSION Use the VERSION runtime, instead of autodetecting\n"
1622 " --optimize=OPT Turns on or off a specific optimization\n"
1623 " Use --list-opt to get a list of optimizations\n"
1624 " --attach=OPTIONS Pass OPTIONS to the attach agent in the runtime.\n"
1625 " Currently the only supported option is 'disable'.\n"
1626 " --llvm, --nollvm Controls whenever the runtime uses LLVM to compile code.\n"
1627 " --gc=[sgen,boehm] Select SGen or Boehm GC (runs mono or mono-sgen)\n"
1628 #ifdef TARGET_OSX
1629 " --arch=[32,64] Select architecture (runs mono32 or mono64)\n"
1630 #endif
1631 #ifdef HOST_WIN32
1632 " --mixed-mode Enable mixed-mode image support.\n"
1633 #endif
1634 " --handlers Install custom handlers, use --help-handlers for details.\n"
1635 " --aot-path=PATH List of additional directories to search for AOT images.\n"
1639 static void
1640 mini_trace_usage (void)
1642 fprintf (stdout,
1643 "Tracing options:\n"
1644 " --trace[=EXPR] Trace every call, optional EXPR controls the scope\n"
1645 "\n"
1646 "EXPR is composed of:\n"
1647 " all All assemblies\n"
1648 " none No assemblies\n"
1649 " program Entry point assembly\n"
1650 " assembly Specifies an assembly\n"
1651 " wrapper All wrappers bridging native and managed code\n"
1652 " M:Type:Method Specifies a method\n"
1653 " N:Namespace Specifies a namespace\n"
1654 " T:Type Specifies a type\n"
1655 " E:Type Specifies stack traces for an exception type\n"
1656 " EXPR Includes expression\n"
1657 " -EXPR Excludes expression\n"
1658 " EXPR,EXPR Multiple expressions\n"
1659 " disabled Don't print any output until toggled via SIGUSR2\n");
1662 static void
1663 mini_debug_usage (void)
1665 fprintf (stdout,
1666 "Debugging options:\n"
1667 " --debug[=OPTIONS] Enable debugging support, optional OPTIONS is a comma\n"
1668 " separated list of options\n"
1669 "\n"
1670 "OPTIONS is composed of:\n"
1671 " casts Enable more detailed InvalidCastException messages.\n"
1672 " mdb-optimizations Disable some JIT optimizations which are normally\n"
1673 " disabled when running inside the debugger.\n"
1674 " This is useful if you plan to attach to the running\n"
1675 " process with the debugger.\n");
1678 #if defined(MONO_ARCH_ARCHITECTURE)
1679 /* Redefine MONO_ARCHITECTURE to include more information */
1680 #undef MONO_ARCHITECTURE
1681 #define MONO_ARCHITECTURE MONO_ARCH_ARCHITECTURE
1682 #endif
1684 static char *
1685 mono_get_version_info (void)
1687 GString *output;
1688 output = g_string_new ("");
1690 #ifdef MONO_KEYWORD_THREAD
1691 g_string_append_printf (output, "\tTLS: __thread\n");
1692 #else
1693 g_string_append_printf (output, "\tTLS: \n");
1694 #endif /* MONO_KEYWORD_THREAD */
1696 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
1697 g_string_append_printf (output, "\tSIGSEGV: altstack\n");
1698 #else
1699 g_string_append_printf (output, "\tSIGSEGV: normal\n");
1700 #endif
1702 #ifdef HAVE_EPOLL
1703 g_string_append_printf (output, "\tNotifications: epoll\n");
1704 #elif defined(HAVE_KQUEUE)
1705 g_string_append_printf (output, "\tNotification: kqueue\n");
1706 #else
1707 g_string_append_printf (output, "\tNotification: Thread + polling\n");
1708 #endif
1710 g_string_append_printf (output, "\tArchitecture: %s\n", MONO_ARCHITECTURE);
1711 g_string_append_printf (output, "\tDisabled: %s\n", DISABLED_FEATURES);
1713 g_string_append_printf (output, "\tMisc: ");
1714 #ifdef MONO_SMALL_CONFIG
1715 g_string_append_printf (output, "smallconfig ");
1716 #endif
1718 #ifdef MONO_BIG_ARRAYS
1719 g_string_append_printf (output, "bigarrays ");
1720 #endif
1722 #if !defined(DISABLE_SDB)
1723 g_string_append_printf (output, "softdebug ");
1724 #endif
1725 g_string_append_printf (output, "\n");
1727 #ifndef DISABLE_INTERPRETER
1728 g_string_append_printf (output, "\tInterpreter: yes\n");
1729 #else
1730 g_string_append_printf (output, "\tInterpreter: no\n");
1731 #endif
1733 #ifdef MONO_ARCH_LLVM_SUPPORTED
1734 #ifdef ENABLE_LLVM
1735 g_string_append_printf (output, "\tLLVM: yes(%d)\n", LLVM_API_VERSION);
1736 #else
1737 g_string_append_printf (output, "\tLLVM: supported, not enabled.\n");
1738 #endif
1739 #endif
1741 mono_threads_suspend_policy_init ();
1742 g_string_append_printf (output, "\tSuspend: %s\n", mono_threads_suspend_policy_name (mono_threads_suspend_policy ()));
1744 return g_string_free (output, FALSE);
1747 #ifndef MONO_ARCH_AOT_SUPPORTED
1748 #define error_if_aot_unsupported() do {fprintf (stderr, "AOT compilation is not supported on this platform.\n"); exit (1);} while (0)
1749 #else
1750 #define error_if_aot_unsupported()
1751 #endif
1753 static gboolean enable_debugging;
1756 * mono_jit_parse_options:
1758 * Process the command line options in \p argv as done by the runtime executable.
1759 * This should be called before \c mono_jit_init.
1761 void
1762 mono_jit_parse_options (int argc, char * argv[])
1764 int i;
1765 char *trace_options = NULL;
1766 int mini_verbose_level = 0;
1767 guint32 opt;
1770 * Some options have no effect here, since they influence the behavior of
1771 * mono_main ().
1774 opt = mono_parse_default_optimizations (NULL);
1776 /* FIXME: Avoid code duplication */
1777 for (i = 0; i < argc; ++i) {
1778 if (argv [i] [0] != '-')
1779 break;
1780 if (strncmp (argv [i], "--debugger-agent=", 17) == 0) {
1781 MonoDebugOptions *opt = mini_get_debug_options ();
1783 sdb_options = g_strdup (argv [i] + 17);
1784 opt->mdb_optimizations = TRUE;
1785 enable_debugging = TRUE;
1786 } else if (!strcmp (argv [i], "--soft-breakpoints")) {
1787 MonoDebugOptions *opt = mini_get_debug_options ();
1789 opt->soft_breakpoints = TRUE;
1790 opt->explicit_null_checks = TRUE;
1791 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
1792 opt = parse_optimizations (opt, argv [i] + 11, TRUE);
1793 mono_set_optimizations (opt);
1794 } else if (strncmp (argv [i], "-O=", 3) == 0) {
1795 opt = parse_optimizations (opt, argv [i] + 3, TRUE);
1796 mono_set_optimizations (opt);
1797 } else if (strcmp (argv [i], "--trace") == 0) {
1798 trace_options = (char*)"";
1799 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
1800 trace_options = &argv [i][8];
1801 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
1802 mini_verbose_level++;
1803 } else if (strcmp (argv [i], "--breakonex") == 0) {
1804 MonoDebugOptions *opt = mini_get_debug_options ();
1806 opt->break_on_exc = TRUE;
1807 } else if (strcmp (argv [i], "--stats") == 0) {
1808 mono_counters_enable (-1);
1809 mono_atomic_store_bool (&mono_stats.enabled, TRUE);
1810 mono_atomic_store_bool (&mono_jit_stats.enabled, TRUE);
1811 } else if (strcmp (argv [i], "--break") == 0) {
1812 if (i+1 >= argc){
1813 fprintf (stderr, "Missing method name in --break command line option\n");
1814 exit (1);
1817 if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
1818 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
1819 } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
1820 mono_gc_params_set (argv[i] + 12);
1821 } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
1822 mono_gc_debug_set (argv[i] + 11);
1823 } else if (strcmp (argv [i], "--llvm") == 0) {
1824 #ifndef MONO_ARCH_LLVM_SUPPORTED
1825 fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
1826 #elif !defined(ENABLE_LLVM)
1827 fprintf (stderr, "Mono Warning: --llvm not enabled in this runtime.\n");
1828 #else
1829 mono_use_llvm = TRUE;
1830 #endif
1831 } else if (argv [i][0] == '-' && argv [i][1] == '-' && mini_parse_debug_option (argv [i] + 2)) {
1832 } else {
1833 fprintf (stderr, "Unsupported command line option: '%s'\n", argv [i]);
1834 exit (1);
1838 if (trace_options != NULL) {
1840 * Need to call this before mini_init () so we can trace methods
1841 * compiled there too.
1843 mono_jit_trace_calls = mono_trace_set_options (trace_options);
1844 if (mono_jit_trace_calls == NULL)
1845 exit (1);
1848 if (mini_verbose_level)
1849 mono_set_verbose_level (mini_verbose_level);
1852 static void
1853 mono_set_use_smp (int use_smp)
1855 #if HAVE_SCHED_SETAFFINITY
1856 if (!use_smp) {
1857 unsigned long proc_mask = 1;
1858 #ifdef GLIBC_BEFORE_2_3_4_SCHED_SETAFFINITY
1859 sched_setaffinity (getpid(), (gpointer)&proc_mask);
1860 #else
1861 sched_setaffinity (getpid(), sizeof (unsigned long), (const cpu_set_t *)&proc_mask);
1862 #endif
1864 #endif
1867 static void
1868 switch_gc (char* argv[], const char* target_gc)
1870 GString *path;
1872 if (!strcmp (mono_gc_get_gc_name (), target_gc)) {
1873 return;
1876 path = g_string_new (argv [0]);
1878 /*Running mono without any argument*/
1879 if (strstr (argv [0], "-sgen"))
1880 g_string_truncate (path, path->len - 5);
1881 else if (strstr (argv [0], "-boehm"))
1882 g_string_truncate (path, path->len - 6);
1884 g_string_append_c (path, '-');
1885 g_string_append (path, target_gc);
1887 #ifdef HAVE_EXECVP
1888 execvp (path->str, argv);
1889 fprintf (stderr, "Error: Failed to switch to %s gc. mono-%s is not installed.\n", target_gc, target_gc);
1890 #else
1891 fprintf (stderr, "Error: --gc=<NAME> option not supported on this platform.\n");
1892 #endif
1895 #ifdef TARGET_OSX
1898 * tries to increase the minimum number of files, if the number is below 1024
1900 static void
1901 darwin_change_default_file_handles ()
1903 struct rlimit limit;
1905 if (getrlimit (RLIMIT_NOFILE, &limit) == 0){
1906 if (limit.rlim_cur < 1024){
1907 limit.rlim_cur = MAX(1024,limit.rlim_cur);
1908 setrlimit (RLIMIT_NOFILE, &limit);
1913 static void
1914 switch_arch (char* argv[], const char* target_arch)
1916 GString *path;
1917 gsize arch_offset;
1919 if ((strcmp (target_arch, "32") == 0 && strcmp (MONO_ARCHITECTURE, "x86") == 0) ||
1920 (strcmp (target_arch, "64") == 0 && strcmp (MONO_ARCHITECTURE, "amd64") == 0)) {
1921 return; /* matching arch loaded */
1924 path = g_string_new (argv [0]);
1925 arch_offset = path->len -2; /* last two characters */
1927 /* Remove arch suffix if present */
1928 if (strstr (&path->str[arch_offset], "32") || strstr (&path->str[arch_offset], "64")) {
1929 g_string_truncate (path, arch_offset);
1932 g_string_append (path, target_arch);
1934 if (execvp (path->str, argv) < 0) {
1935 fprintf (stderr, "Error: --arch=%s Failed to switch to '%s'.\n", target_arch, path->str);
1936 exit (1);
1940 #endif
1942 #define MONO_HANDLERS_ARGUMENT "--handlers="
1943 #define MONO_HANDLERS_ARGUMENT_LEN G_N_ELEMENTS(MONO_HANDLERS_ARGUMENT)-1
1945 static void
1946 apply_root_domain_configuration_file_bindings (MonoDomain *domain, char *root_domain_configuration_file)
1948 g_assert (domain->setup == NULL || domain->setup->configuration_file == NULL);
1949 g_assert (!domain->assembly_bindings_parsed);
1951 mono_domain_parse_assembly_bindings (domain, 0, 0, root_domain_configuration_file);
1955 static void
1956 mono_check_interp_supported (void)
1958 #ifdef DISABLE_INTERPRETER
1959 g_error ("Mono IL interpreter support is missing\n");
1960 #endif
1962 #ifdef MONO_CROSS_COMPILE
1963 g_error ("--interpreter on cross-compile runtimes not supported\n");
1964 #endif
1966 #ifndef MONO_ARCH_INTERPRETER_SUPPORTED
1967 g_error ("--interpreter not supported on this architecture.\n");
1968 #endif
1971 static int
1972 mono_exec_regression_internal (int verbose_level, int count, char *images [], gboolean single_method)
1974 mono_do_single_method_regression = single_method;
1975 if (mono_use_interpreter) {
1976 if (mono_interp_regression_list (verbose_level, count, images)) {
1977 g_print ("Regression ERRORS!\n");
1978 return 1;
1980 return 0;
1982 if (mini_regression_list (verbose_level, count, images)) {
1983 g_print ("Regression ERRORS!\n");
1984 return 1;
1986 return 0;
1991 * Returns TRUE for success, FALSE for failure.
1993 gboolean
1994 mono_regression_test_step (int verbose_level, const char *image, const char *method_name)
1996 if (method_name) {
1997 //TODO
1998 } else {
1999 do_regression_retries = TRUE;
2002 char *images[] = {
2003 (char*)image,
2004 NULL
2007 return mono_exec_regression_internal (verbose_level, 1, images, FALSE) == 0;
2010 #ifdef ENABLE_ICALL_SYMBOL_MAP
2011 /* Print the icall table as JSON */
2012 static void
2013 print_icall_table (void)
2015 // We emit some dummy values to make the code simpler
2017 printf ("[\n{ \"klass\": \"\", \"icalls\": [");
2018 #define NOHANDLES(inner) inner
2019 #define HANDLES(id, name, func, ...) printf ("\t,{ \"name\": \"%s\", \"func\": \"%s_raw\", \"handles\": true }\n", name, #func);
2020 #define HANDLES_REUSE_WRAPPER HANDLES
2021 #define MONO_HANDLE_REGISTER_ICALL(...) /* nothing */
2022 #define ICALL_TYPE(id,name,first) printf ("]},\n { \"klass\":\"%s\", \"icalls\": [{} ", name);
2023 #define ICALL(id,name,func) printf ("\t,{ \"name\": \"%s\", \"func\": \"%s\", \"handles\": false }\n", name, #func);
2024 #include <mono/metadata/icall-def.h>
2026 printf ("]}\n]\n");
2028 #endif
2031 * mono_main:
2032 * \param argc number of arguments in the argv array
2033 * \param argv array of strings containing the startup arguments
2034 * Launches the Mono JIT engine and parses all the command line options
2035 * in the same way that the mono command line VM would.
2038 mono_main (int argc, char* argv[])
2040 MainThreadArgs main_args;
2041 MonoAssembly *assembly;
2042 MonoMethodDesc *desc;
2043 MonoMethod *method;
2044 MonoDomain *domain;
2045 MonoImageOpenStatus open_status;
2046 const char* aname, *mname = NULL;
2047 char *config_file = NULL;
2048 int i, count = 1;
2049 guint32 opt, action = DO_EXEC, recompilation_times = 1;
2050 MonoGraphOptions mono_graph_options = (MonoGraphOptions)0;
2051 int mini_verbose_level = 0;
2052 char *trace_options = NULL;
2053 char *aot_options = NULL;
2054 char *forced_version = NULL;
2055 GPtrArray *agents = NULL;
2056 char *attach_options = NULL;
2057 char *extra_bindings_config_file = NULL;
2058 #ifdef MONO_JIT_INFO_TABLE_TEST
2059 int test_jit_info_table = FALSE;
2060 #endif
2061 #ifdef HOST_WIN32
2062 int mixed_mode = FALSE;
2063 #endif
2065 #ifdef MOONLIGHT
2066 #ifndef HOST_WIN32
2067 /* stdout defaults to block buffering if it's not writing to a terminal, which
2068 * happens with our test harness: we redirect stdout to capture it. Force line
2069 * buffering in all cases. */
2070 setlinebuf (stdout);
2071 #endif
2072 #endif
2074 setlocale (LC_ALL, "");
2076 #if TARGET_OSX
2077 darwin_change_default_file_handles ();
2078 #endif
2080 if (g_hasenv ("MONO_NO_SMP"))
2081 mono_set_use_smp (FALSE);
2083 #ifdef MONO_JEMALLOC_ENABLED
2085 gboolean use_jemalloc = FALSE;
2086 #ifdef MONO_JEMALLOC_DEFAULT
2087 use_jemalloc = TRUE;
2088 #endif
2089 if (!use_jemalloc)
2090 use_jemalloc = g_hasenv ("MONO_USE_JEMALLOC");
2092 if (use_jemalloc)
2093 mono_init_jemalloc ();
2095 #endif
2097 g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
2098 g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
2100 opt = mono_parse_default_optimizations (NULL);
2102 for (i = 1; i < argc; ++i) {
2103 if (argv [i] [0] != '-')
2104 break;
2105 if (strcmp (argv [i], "--regression") == 0) {
2106 action = DO_REGRESSION;
2107 } else if (strncmp (argv [i], "--single-method=", 16) == 0) {
2108 char *full_opts = g_strdup_printf ("-all,%s", argv [i] + 16);
2109 action = DO_SINGLE_METHOD_REGRESSION;
2110 mono_single_method_regression_opt = parse_optimizations (opt, full_opts, TRUE);
2111 g_free (full_opts);
2112 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
2113 mini_verbose_level++;
2114 } else if (strcmp (argv [i], "--version=number") == 0) {
2115 g_print ("%s\n", VERSION);
2116 return 0;
2117 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
2118 char *build = mono_get_runtime_build_info ();
2119 char *gc_descr;
2121 g_print ("Mono JIT compiler version %s\nCopyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com\n", build);
2122 g_free (build);
2123 char *info = mono_get_version_info ();
2124 g_print (info);
2125 g_free (info);
2127 gc_descr = mono_gc_get_description ();
2128 g_print ("\tGC: %s\n", gc_descr);
2129 g_free (gc_descr);
2130 return 0;
2131 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
2132 mini_usage ();
2133 return 0;
2134 } else if (strcmp (argv [i], "--help-trace") == 0){
2135 mini_trace_usage ();
2136 return 0;
2137 } else if (strcmp (argv [i], "--help-devel") == 0){
2138 mini_usage_jitdeveloper ();
2139 return 0;
2140 } else if (strcmp (argv [i], "--help-debug") == 0){
2141 mini_debug_usage ();
2142 return 0;
2143 } else if (strcmp (argv [i], "--list-opt") == 0){
2144 mini_usage_list_opt ();
2145 return 0;
2146 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
2147 if (i + 1 >= argc){
2148 fprintf (stderr, "error: --statfile requires a filename argument\n");
2149 return 1;
2151 mini_stats_fd = fopen (argv [++i], "w+");
2152 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
2153 opt = parse_optimizations (opt, argv [i] + 11, TRUE);
2154 } else if (strncmp (argv [i], "-O=", 3) == 0) {
2155 opt = parse_optimizations (opt, argv [i] + 3, TRUE);
2156 } else if (strncmp (argv [i], "--bisect=", 9) == 0) {
2157 char *param = argv [i] + 9;
2158 char *sep = strchr (param, ':');
2159 if (!sep) {
2160 fprintf (stderr, "Error: --bisect requires OPT:FILENAME\n");
2161 return 1;
2163 char *opt_string = g_strndup (param, sep - param);
2164 guint32 opt = parse_optimizations (0, opt_string, FALSE);
2165 g_free (opt_string);
2166 mono_set_bisect_methods (opt, sep + 1);
2167 } else if (strcmp (argv [i], "--gc=sgen") == 0) {
2168 switch_gc (argv, "sgen");
2169 } else if (strcmp (argv [i], "--gc=boehm") == 0) {
2170 switch_gc (argv, "boehm");
2171 } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
2172 mono_gc_params_set (argv[i] + 12);
2173 } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
2174 mono_gc_debug_set (argv[i] + 11);
2176 #ifdef TARGET_OSX
2177 else if (strcmp (argv [i], "--arch=32") == 0) {
2178 switch_arch (argv, "32");
2179 } else if (strcmp (argv [i], "--arch=64") == 0) {
2180 switch_arch (argv, "64");
2182 #endif
2183 else if (strcmp (argv [i], "--config") == 0) {
2184 if (i +1 >= argc){
2185 fprintf (stderr, "error: --config requires a filename argument\n");
2186 return 1;
2188 config_file = argv [++i];
2189 #ifdef HOST_WIN32
2190 } else if (strcmp (argv [i], "--mixed-mode") == 0) {
2191 mixed_mode = TRUE;
2192 #endif
2193 } else if (strcmp (argv [i], "--ncompile") == 0) {
2194 if (i + 1 >= argc){
2195 fprintf (stderr, "error: --ncompile requires an argument\n");
2196 return 1;
2198 count = atoi (argv [++i]);
2199 action = DO_BENCH;
2200 } else if (strcmp (argv [i], "--trace") == 0) {
2201 trace_options = (char*)"";
2202 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
2203 trace_options = &argv [i][8];
2204 } else if (strcmp (argv [i], "--breakonex") == 0) {
2205 MonoDebugOptions *opt = mini_get_debug_options ();
2207 opt->break_on_exc = TRUE;
2208 } else if (strcmp (argv [i], "--break") == 0) {
2209 if (i+1 >= argc){
2210 fprintf (stderr, "Missing method name in --break command line option\n");
2211 return 1;
2214 if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
2215 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
2216 } else if (strcmp (argv [i], "--break-at-bb") == 0) {
2217 if (i + 2 >= argc) {
2218 fprintf (stderr, "Missing method name or bb num in --break-at-bb command line option.");
2219 return 1;
2221 mono_break_at_bb_method = mono_method_desc_new (argv [++i], TRUE);
2222 if (mono_break_at_bb_method == NULL) {
2223 fprintf (stderr, "Method name is in a bad format in --break-at-bb command line option.");
2224 return 1;
2226 mono_break_at_bb_bb_num = atoi (argv [++i]);
2227 } else if (strcmp (argv [i], "--inject-async-exc") == 0) {
2228 if (i + 2 >= argc) {
2229 fprintf (stderr, "Missing method name or position in --inject-async-exc command line option\n");
2230 return 1;
2232 mono_inject_async_exc_method = mono_method_desc_new (argv [++i], TRUE);
2233 if (mono_inject_async_exc_method == NULL) {
2234 fprintf (stderr, "Method name is in a bad format in --inject-async-exc command line option\n");
2235 return 1;
2237 mono_inject_async_exc_pos = atoi (argv [++i]);
2238 } else if (strcmp (argv [i], "--verify-all") == 0) {
2239 mono_verifier_enable_verify_all ();
2240 } else if (strcmp (argv [i], "--full-aot") == 0) {
2241 mono_jit_set_aot_mode (MONO_AOT_MODE_FULL);
2242 } else if (strcmp (argv [i], "--llvmonly") == 0) {
2243 mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY);
2244 } else if (strcmp (argv [i], "--hybrid-aot") == 0) {
2245 mono_jit_set_aot_mode (MONO_AOT_MODE_HYBRID);
2246 } else if (strcmp (argv [i], "--full-aot-interp") == 0) {
2247 mono_jit_set_aot_mode (MONO_AOT_MODE_INTERP);
2248 } else if (strcmp (argv [i], "--llvmonly-interp") == 0) {
2249 mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY_INTERP);
2250 } else if (strcmp (argv [i], "--print-vtable") == 0) {
2251 mono_print_vtable = TRUE;
2252 } else if (strcmp (argv [i], "--stats") == 0) {
2253 mono_counters_enable (-1);
2254 mono_atomic_store_bool (&mono_stats.enabled, TRUE);
2255 mono_atomic_store_bool (&mono_jit_stats.enabled, TRUE);
2256 #ifndef DISABLE_AOT
2257 } else if (strcmp (argv [i], "--aot") == 0) {
2258 error_if_aot_unsupported ();
2259 mono_compile_aot = TRUE;
2260 } else if (strncmp (argv [i], "--aot=", 6) == 0) {
2261 error_if_aot_unsupported ();
2262 mono_compile_aot = TRUE;
2263 if (aot_options) {
2264 char *tmp = g_strdup_printf ("%s,%s", aot_options, &argv [i][6]);
2265 g_free (aot_options);
2266 aot_options = tmp;
2267 } else {
2268 aot_options = g_strdup (&argv [i][6]);
2270 #endif
2271 } else if (strncmp (argv [i], "--apply-bindings=", 17) == 0) {
2272 extra_bindings_config_file = &argv[i][17];
2273 } else if (strncmp (argv [i], "--aot-path=", 11) == 0) {
2274 char **splitted;
2276 splitted = g_strsplit (argv [i] + 11, G_SEARCHPATH_SEPARATOR_S, 1000);
2277 while (*splitted) {
2278 char *tmp = *splitted;
2279 mono_aot_paths = g_list_append (mono_aot_paths, g_strdup (tmp));
2280 g_free (tmp);
2281 splitted++;
2283 } else if (strncmp (argv [i], "--compile-all=", 14) == 0) {
2284 action = DO_COMPILE;
2285 recompilation_times = atoi (argv [i] + 14);
2286 } else if (strcmp (argv [i], "--compile-all") == 0) {
2287 action = DO_COMPILE;
2288 } else if (strncmp (argv [i], "--runtime=", 10) == 0) {
2289 forced_version = &argv [i][10];
2290 } else if (strcmp (argv [i], "--jitmap") == 0) {
2291 mono_enable_jit_map ();
2292 } else if (strcmp (argv [i], "--profile") == 0) {
2293 mini_add_profiler_argument (NULL);
2294 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
2295 mini_add_profiler_argument (argv [i] + 10);
2296 } else if (strncmp (argv [i], "--agent=", 8) == 0) {
2297 if (agents == NULL)
2298 agents = g_ptr_array_new ();
2299 g_ptr_array_add (agents, argv [i] + 8);
2300 } else if (strncmp (argv [i], "--attach=", 9) == 0) {
2301 attach_options = argv [i] + 9;
2302 } else if (strcmp (argv [i], "--compile") == 0) {
2303 if (i + 1 >= argc){
2304 fprintf (stderr, "error: --compile option requires a method name argument\n");
2305 return 1;
2308 mname = argv [++i];
2309 action = DO_BENCH;
2310 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
2311 if (i + 1 >= argc){
2312 fprintf (stderr, "error: --graph option requires a method name argument\n");
2313 return 1;
2316 mono_graph_options = mono_parse_graph_options (argv [i] + 8);
2317 mname = argv [++i];
2318 action = DO_DRAW;
2319 } else if (strcmp (argv [i], "--graph") == 0) {
2320 if (i + 1 >= argc){
2321 fprintf (stderr, "error: --graph option requires a method name argument\n");
2322 return 1;
2325 mname = argv [++i];
2326 mono_graph_options = MONO_GRAPH_CFG;
2327 action = DO_DRAW;
2328 } else if (strcmp (argv [i], "--debug") == 0) {
2329 enable_debugging = TRUE;
2330 } else if (strncmp (argv [i], "--debug=", 8) == 0) {
2331 enable_debugging = TRUE;
2332 if (!parse_debug_options (argv [i] + 8))
2333 return 1;
2334 } else if (strncmp (argv [i], "--debugger-agent=", 17) == 0) {
2335 MonoDebugOptions *opt = mini_get_debug_options ();
2337 sdb_options = g_strdup (argv [i] + 17);
2338 opt->mdb_optimizations = TRUE;
2339 enable_debugging = TRUE;
2340 } else if (strcmp (argv [i], "--security") == 0) {
2341 #ifndef DISABLE_SECURITY
2342 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2343 #else
2344 fprintf (stderr, "error: --security: not compiled with security manager support");
2345 return 1;
2346 #endif
2347 } else if (strncmp (argv [i], "--security=", 11) == 0) {
2348 /* Note: validil, and verifiable need to be
2349 accepted even if DISABLE_SECURITY is defined. */
2351 if (strcmp (argv [i] + 11, "core-clr") == 0) {
2352 #ifndef DISABLE_SECURITY
2353 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2354 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
2355 #else
2356 fprintf (stderr, "error: --security: not compiled with CoreCLR support");
2357 return 1;
2358 #endif
2359 } else if (strcmp (argv [i] + 11, "core-clr-test") == 0) {
2360 #ifndef DISABLE_SECURITY
2361 /* fixme should we enable verifiable code here?*/
2362 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
2363 mono_security_core_clr_test = TRUE;
2364 #else
2365 fprintf (stderr, "error: --security: not compiled with CoreCLR support");
2366 return 1;
2367 #endif
2368 } else if (strcmp (argv [i] + 11, "cas") == 0) {
2369 #ifndef DISABLE_SECURITY
2370 fprintf (stderr, "warning: --security=cas not supported.");
2371 #else
2372 fprintf (stderr, "error: --security: not compiled with CAS support");
2373 return 1;
2374 #endif
2375 } else if (strcmp (argv [i] + 11, "validil") == 0) {
2376 mono_verifier_set_mode (MONO_VERIFIER_MODE_VALID);
2377 } else if (strcmp (argv [i] + 11, "verifiable") == 0) {
2378 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2379 } else {
2380 fprintf (stderr, "error: --security= option has invalid argument (cas, core-clr, verifiable or validil)\n");
2381 return 1;
2383 } else if (strcmp (argv [i], "--desktop") == 0) {
2384 mono_gc_set_desktop_mode ();
2385 /* Put more desktop-specific optimizations here */
2386 } else if (strcmp (argv [i], "--server") == 0){
2387 mono_config_set_server_mode (TRUE);
2388 /* Put more server-specific optimizations here */
2389 } else if (strcmp (argv [i], "--inside-mdb") == 0) {
2390 action = DO_DEBUGGER;
2391 } else if (strncmp (argv [i], "--wapi=", 7) == 0) {
2392 fprintf (stderr, "--wapi= option no longer supported\n.");
2393 return 1;
2394 } else if (strcmp (argv [i], "--no-x86-stack-align") == 0) {
2395 mono_do_x86_stack_align = FALSE;
2396 #ifdef MONO_JIT_INFO_TABLE_TEST
2397 } else if (strcmp (argv [i], "--test-jit-info-table") == 0) {
2398 test_jit_info_table = TRUE;
2399 #endif
2400 } else if (strcmp (argv [i], "--llvm") == 0) {
2401 #ifndef MONO_ARCH_LLVM_SUPPORTED
2402 fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
2403 #elif !defined(ENABLE_LLVM)
2404 fprintf (stderr, "Mono Warning: --llvm not enabled in this runtime.\n");
2405 #else
2406 mono_use_llvm = TRUE;
2407 #endif
2408 } else if (strcmp (argv [i], "--nollvm") == 0){
2409 mono_use_llvm = FALSE;
2410 } else if (strcmp (argv [i], "--ffast-math") == 0){
2411 mono_use_fast_math = TRUE;
2412 } else if ((strcmp (argv [i], "--interpreter") == 0) || !strcmp (argv [i], "--interp")) {
2413 mono_runtime_set_execution_mode (MONO_EE_MODE_INTERP);
2414 } else if (strncmp (argv [i], "--interp=", 9) == 0) {
2415 mono_runtime_set_execution_mode_full (MONO_EE_MODE_INTERP, FALSE);
2416 mono_interp_opts_string = argv [i] + 9;
2417 } else if (strcmp (argv [i], "--print-icall-table") == 0) {
2418 #ifdef ENABLE_ICALL_SYMBOL_MAP
2419 print_icall_table ();
2420 exit (0);
2421 #else
2422 fprintf (stderr, "--print-icall-table requires a runtime configured with the --enable-icall-symbol-map option.\n");
2423 exit (1);
2424 #endif
2425 } else if (strncmp (argv [i], "--assembly-loader=", strlen("--assembly-loader=")) == 0) {
2426 gchar *arg = argv [i] + strlen ("--assembly-loader=");
2427 if (strcmp (arg, "strict") == 0)
2428 mono_loader_set_strict_assembly_name_check (TRUE);
2429 else if (strcmp (arg, "legacy") == 0)
2430 mono_loader_set_strict_assembly_name_check (FALSE);
2431 else
2432 fprintf (stderr, "Warning: unknown argument to --assembly-loader. Should be \"strict\" or \"legacy\"\n");
2433 } else if (strncmp (argv [i], MONO_HANDLERS_ARGUMENT, MONO_HANDLERS_ARGUMENT_LEN) == 0) {
2434 //Install specific custom handlers.
2435 if (!mono_runtime_install_custom_handlers (argv[i] + MONO_HANDLERS_ARGUMENT_LEN)) {
2436 fprintf (stderr, "error: " MONO_HANDLERS_ARGUMENT ", one or more unknown handlers: '%s'\n", argv [i]);
2437 return 1;
2439 } else if (strcmp (argv [i], "--help-handlers") == 0) {
2440 mono_runtime_install_custom_handlers_usage ();
2441 return 0;
2442 } else if (strncmp (argv [i], "--response=", 11) == 0){
2443 gchar *response_content;
2444 gchar *response_options;
2445 gsize response_content_len;
2447 if (!g_file_get_contents (&argv[i][11], &response_content, &response_content_len, NULL)){
2448 fprintf (stderr, "The specified response file can not be read\n");
2449 exit (1);
2452 response_options = response_content;
2454 // Check for UTF8 BOM in file and remove if found.
2455 if (response_content_len >= 3 && response_content [0] == '\xef' && response_content [1] == '\xbb' && response_content [2] == '\xbf') {
2456 response_content_len -= 3;
2457 response_options += 3;
2460 if (response_content_len == 0) {
2461 fprintf (stderr, "The specified response file is empty\n");
2462 exit (1);
2465 mono_parse_response_options (response_options, &argc, &argv, FALSE);
2466 g_free (response_content);
2467 } else if (argv [i][0] == '-' && argv [i][1] == '-' && mini_parse_debug_option (argv [i] + 2)) {
2468 } else if (strcmp (argv [i], "--use-map-jit") == 0){
2469 mono_setmmapjit (TRUE);
2470 } else {
2471 fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
2472 return 1;
2476 #if defined(DISABLE_HW_TRAPS) || defined(MONO_ARCH_DISABLE_HW_TRAPS)
2477 // Signal handlers not available
2479 MonoDebugOptions *opt = mini_get_debug_options ();
2480 opt->explicit_null_checks = TRUE;
2482 #endif
2484 if (!argv [i]) {
2485 mini_usage ();
2486 return 1;
2490 * XXX: verify if other OSes need it; many platforms seem to have it so that
2491 * mono_w32process_get_path -> mono_w32process_get_name, and the name is not
2492 * necessarily a path instead of just the program name
2494 #if defined (_AIX)
2496 * mono_w32process_get_path on these can only return a name, not a path;
2497 * which may not be good for us if the mono command name isn't on $PATH,
2498 * like in CI scenarios. chances are argv based is fine if we inherited
2499 * the environment variables.
2501 mono_w32process_set_cli_launcher (argv [0]);
2502 #elif !defined(HOST_WIN32) && defined(HAVE_UNISTD_H)
2504 * If we are not embedded, use the mono runtime executable to run managed exe's.
2507 char *runtime_path;
2509 runtime_path = mono_w32process_get_path (getpid ());
2510 if (runtime_path) {
2511 mono_w32process_set_cli_launcher (runtime_path);
2512 g_free (runtime_path);
2515 #endif
2517 if (g_hasenv ("MONO_XDEBUG"))
2518 enable_debugging = TRUE;
2520 #ifdef MONO_CROSS_COMPILE
2521 if (!mono_compile_aot) {
2522 fprintf (stderr, "This mono runtime is compiled for cross-compiling. Only the --aot option is supported.\n");
2523 exit (1);
2525 #if TARGET_SIZEOF_VOID_P == 4 && (defined(TARGET_ARM64) || defined(TARGET_AMD64)) && !defined(MONO_ARCH_ILP32)
2526 fprintf (stderr, "Can't cross-compile on 32-bit platforms to 64-bit architecture.\n");
2527 exit (1);
2528 #endif
2529 #endif
2531 if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
2532 g_set_prgname (argv[i]);
2535 mono_counters_init ();
2537 #ifndef HOST_WIN32
2538 mono_w32handle_init ();
2539 #endif
2541 /* Set rootdir before loading config */
2542 mono_set_rootdir ();
2544 mono_attach_parse_options (attach_options);
2546 if (trace_options != NULL){
2548 * Need to call this before mini_init () so we can trace methods
2549 * compiled there too.
2551 mono_jit_trace_calls = mono_trace_set_options (trace_options);
2552 if (mono_jit_trace_calls == NULL)
2553 exit (1);
2556 #ifdef DISABLE_JIT
2557 if (!mono_aot_only && !mono_use_interpreter) {
2558 fprintf (stderr, "This runtime has been configured with --enable-minimal=jit, so the --full-aot command line option is required.\n");
2559 exit (1);
2561 #endif
2563 if (action == DO_DEBUGGER) {
2564 enable_debugging = TRUE;
2565 g_print ("The Mono Debugger is no longer supported.\n");
2566 return 1;
2567 } else if (enable_debugging)
2568 mono_debug_init (MONO_DEBUG_FORMAT_MONO);
2570 #ifdef HOST_WIN32
2571 if (mixed_mode)
2572 mono_load_coree (argv [i]);
2573 #endif
2575 /* Parse gac loading options before loading assemblies. */
2576 if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER || action == DO_REGRESSION) {
2577 mono_config_parse (config_file);
2580 mono_set_defaults (mini_verbose_level, opt);
2581 domain = mini_init (argv [i], forced_version);
2583 mono_gc_set_stack_end (&domain);
2585 if (agents) {
2586 int i;
2588 for (i = 0; i < agents->len; ++i) {
2589 int res = load_agent (domain, (char*)g_ptr_array_index (agents, i));
2590 if (res) {
2591 g_ptr_array_free (agents, TRUE);
2592 mini_cleanup (domain);
2593 return 1;
2597 g_ptr_array_free (agents, TRUE);
2600 switch (action) {
2601 case DO_SINGLE_METHOD_REGRESSION:
2602 case DO_REGRESSION:
2603 return mono_exec_regression_internal (mini_verbose_level, argc -i, argv + i, action == DO_SINGLE_METHOD_REGRESSION);
2605 case DO_BENCH:
2606 if (argc - i != 1 || mname == NULL) {
2607 g_print ("Usage: mini --ncompile num --compile method assembly\n");
2608 mini_cleanup (domain);
2609 return 1;
2611 aname = argv [i];
2612 break;
2613 case DO_COMPILE:
2614 if (argc - i != 1) {
2615 mini_usage ();
2616 mini_cleanup (domain);
2617 return 1;
2619 aname = argv [i];
2620 break;
2621 case DO_DRAW:
2622 if (argc - i != 1 || mname == NULL) {
2623 mini_usage ();
2624 mini_cleanup (domain);
2625 return 1;
2627 aname = argv [i];
2628 break;
2629 default:
2630 if (argc - i < 1) {
2631 mini_usage ();
2632 mini_cleanup (domain);
2633 return 1;
2635 aname = argv [i];
2636 break;
2639 #ifdef MONO_JIT_INFO_TABLE_TEST
2640 if (test_jit_info_table)
2641 jit_info_table_test (domain);
2642 #endif
2644 if (mono_compile_aot && extra_bindings_config_file != NULL) {
2645 apply_root_domain_configuration_file_bindings (domain, extra_bindings_config_file);
2648 MonoAssemblyOpenRequest open_req;
2649 mono_assembly_request_prepare_open (&open_req, MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_get_root_domain ()));
2650 assembly = mono_assembly_request_open (aname, &open_req, &open_status);
2651 if (!assembly && !mono_compile_aot) {
2652 fprintf (stderr, "Cannot open assembly '%s': %s.\n", aname, mono_image_strerror (open_status));
2653 mini_cleanup (domain);
2654 return 2;
2657 mono_callspec_set_assembly (assembly);
2659 if (mono_compile_aot || action == DO_EXEC) {
2660 const char *error;
2662 //mono_set_rootdir ();
2664 error = mono_check_corlib_version ();
2665 if (error) {
2666 fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
2667 fprintf (stderr, "Loaded from: %s\n",
2668 mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown");
2669 fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.mono-project.com/download.\n");
2670 exit (1);
2673 #if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
2674 /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
2675 if (!enable_debugging && !mono_compile_aot && mono_assembly_get_image_internal (assembly)->image_info->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
2676 FreeConsole ();
2677 #endif
2679 main_args.domain = domain;
2680 main_args.file = aname;
2681 main_args.argc = argc - i;
2682 main_args.argv = argv + i;
2683 main_args.opts = opt;
2684 main_args.aot_options = aot_options;
2685 main_thread_handler (&main_args);
2686 mono_thread_manage_internal ();
2688 mini_cleanup (domain);
2690 /* Look up return value from System.Environment.ExitCode */
2691 i = mono_environment_exitcode_get ();
2692 return i;
2693 } else if (action == DO_COMPILE) {
2694 compile_all_methods (assembly, mini_verbose_level, opt, recompilation_times);
2695 mini_cleanup (domain);
2696 return 0;
2697 } else if (action == DO_DEBUGGER) {
2698 return 1;
2700 desc = mono_method_desc_new (mname, 0);
2701 if (!desc) {
2702 g_print ("Invalid method name %s\n", mname);
2703 mini_cleanup (domain);
2704 return 3;
2706 method = mono_method_desc_search_in_image (desc, mono_assembly_get_image_internal (assembly));
2707 if (!method) {
2708 g_print ("Cannot find method %s\n", mname);
2709 mini_cleanup (domain);
2710 return 3;
2713 #ifndef DISABLE_JIT
2714 MonoCompile *cfg;
2715 if (action == DO_DRAW) {
2716 int part = 0;
2718 switch (mono_graph_options) {
2719 case MONO_GRAPH_DTREE:
2720 part = 1;
2721 opt |= MONO_OPT_LOOP;
2722 break;
2723 case MONO_GRAPH_CFG_CODE:
2724 part = 1;
2725 break;
2726 case MONO_GRAPH_CFG_SSA:
2727 part = 2;
2728 break;
2729 case MONO_GRAPH_CFG_OPTCODE:
2730 part = 3;
2731 break;
2732 default:
2733 break;
2736 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2737 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
2738 MonoMethod *nm;
2739 nm = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
2740 cfg = mini_method_compile (nm, opt, mono_get_root_domain (), (JitFlags)0, part, -1);
2742 else
2743 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, part, -1);
2744 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
2745 g_warning ("no SSA info available (use -O=deadce)");
2746 return 1;
2748 mono_draw_graph (cfg, mono_graph_options);
2749 mono_destroy_compile (cfg);
2751 } else if (action == DO_BENCH) {
2752 if (mini_stats_fd) {
2753 const char *n;
2754 double no_opt_time = 0.0;
2755 GTimer *timer = g_timer_new ();
2756 fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n",
2757 mono_method_full_name (method, TRUE));
2758 fprintf (mini_stats_fd, "@data = (\n");
2759 fprintf (mini_stats_fd, "[");
2760 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
2761 opt = opt_sets [i];
2762 n = mono_opt_descr (opt);
2763 if (!n [0])
2764 n = "none";
2765 fprintf (mini_stats_fd, "\"%s\",", n);
2767 fprintf (mini_stats_fd, "],\n[");
2769 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
2770 int j;
2771 double elapsed;
2772 opt = opt_sets [i];
2773 g_timer_start (timer);
2774 for (j = 0; j < count; ++j) {
2775 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2776 mono_destroy_compile (cfg);
2778 g_timer_stop (timer);
2779 elapsed = g_timer_elapsed (timer, NULL);
2780 if (!opt)
2781 no_opt_time = elapsed;
2782 fprintf (mini_stats_fd, "%f, ", elapsed);
2784 fprintf (mini_stats_fd, "]");
2785 if (no_opt_time > 0.0) {
2786 fprintf (mini_stats_fd, ", \n[");
2787 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++)
2788 fprintf (mini_stats_fd, "%f,", no_opt_time);
2789 fprintf (mini_stats_fd, "]");
2791 fprintf (mini_stats_fd, ");\n");
2792 } else {
2793 for (i = 0; i < count; ++i) {
2794 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2795 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
2796 method = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
2798 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2799 mono_destroy_compile (cfg);
2802 } else {
2803 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2804 mono_destroy_compile (cfg);
2806 #endif
2808 mini_cleanup (domain);
2809 return 0;
2813 * mono_jit_init:
2815 MonoDomain *
2816 mono_jit_init (const char *file)
2818 MonoDomain *ret = mini_init (file, NULL);
2819 MONO_ENTER_GC_SAFE_UNBALANCED; //once it is not executing any managed code yet, it's safe to run the gc
2820 return ret;
2824 * mono_jit_init_version:
2825 * \param domain_name the name of the root domain
2826 * \param runtime_version the version of the runtime to load
2828 * Use this version when you want to force a particular runtime
2829 * version to be used. By default Mono will pick the runtime that is
2830 * referenced by the initial assembly (specified in \p file), this
2831 * routine allows programmers to specify the actual runtime to be used
2832 * as the initial runtime is inherited by all future assemblies loaded
2833 * (since Mono does not support having more than one mscorlib runtime
2834 * loaded at once).
2836 * The \p runtime_version can be one of these strings: "v4.0.30319" for
2837 * desktop, "mobile" for mobile or "moonlight" for Silverlight compat.
2838 * If an unrecognized string is input, the vm will default to desktop.
2840 * \returns the \c MonoDomain representing the domain where the assembly
2841 * was loaded.
2843 MonoDomain *
2844 mono_jit_init_version (const char *domain_name, const char *runtime_version)
2846 MonoDomain *ret = mini_init (domain_name, runtime_version);
2847 MONO_ENTER_GC_SAFE_UNBALANCED; //once it is not executing any managed code yet, it's safe to run the gc
2848 return ret;
2851 MonoDomain *
2852 mono_jit_init_version_for_test_only (const char *domain_name, const char *runtime_version)
2854 MonoDomain *ret = mini_init (domain_name, runtime_version);
2855 return ret;
2859 * mono_jit_cleanup:
2861 void
2862 mono_jit_cleanup (MonoDomain *domain)
2864 MONO_STACKDATA (dummy);
2865 (void) mono_threads_enter_gc_unsafe_region_unbalanced_internal (&dummy);
2867 // after mini_cleanup everything is cleaned up so MONO_EXIT_GC_UNSAFE
2868 // can't work and doesn't make sense.
2870 mono_thread_manage_internal ();
2872 mini_cleanup (domain);
2876 void
2877 mono_jit_set_aot_only (gboolean val)
2879 mono_aot_only = val;
2880 mono_ee_features.use_aot_trampolines = val;
2883 static void
2884 mono_runtime_set_execution_mode_full (int mode, gboolean override)
2886 static gboolean mode_initialized = FALSE;
2887 if (mode_initialized && !override)
2888 return;
2890 mode_initialized = TRUE;
2891 memset (&mono_ee_features, 0, sizeof (mono_ee_features));
2893 switch (mode) {
2894 case MONO_AOT_MODE_LLVMONLY:
2895 mono_aot_only = TRUE;
2896 mono_llvm_only = TRUE;
2898 mono_ee_features.use_aot_trampolines = TRUE;
2899 break;
2901 case MONO_AOT_MODE_FULL:
2902 mono_aot_only = TRUE;
2904 mono_ee_features.use_aot_trampolines = TRUE;
2905 break;
2907 case MONO_AOT_MODE_HYBRID:
2908 mono_set_generic_sharing_vt_supported (TRUE);
2909 mono_set_partial_sharing_supported (TRUE);
2910 break;
2912 case MONO_AOT_MODE_INTERP:
2913 mono_aot_only = TRUE;
2914 mono_use_interpreter = TRUE;
2916 mono_ee_features.use_aot_trampolines = TRUE;
2917 break;
2919 case MONO_AOT_MODE_INTERP_LLVMONLY:
2920 mono_aot_only = TRUE;
2921 mono_use_interpreter = TRUE;
2922 mono_llvm_only = TRUE;
2924 mono_ee_features.force_use_interpreter = TRUE;
2925 break;
2927 case MONO_AOT_MODE_LLVMONLY_INTERP:
2928 mono_aot_only = TRUE;
2929 mono_use_interpreter = TRUE;
2930 mono_llvm_only = TRUE;
2931 break;
2933 case MONO_EE_MODE_INTERP:
2934 mono_check_interp_supported ();
2935 mono_use_interpreter = TRUE;
2937 mono_ee_features.force_use_interpreter = TRUE;
2938 break;
2940 case MONO_AOT_MODE_NORMAL:
2941 case MONO_AOT_MODE_NONE:
2942 break;
2944 default:
2945 g_error ("Unknown execution-mode %d", mode);
2950 static void
2951 mono_runtime_set_execution_mode (int mode)
2953 mono_runtime_set_execution_mode_full (mode, TRUE);
2957 * mono_jit_set_aot_mode:
2959 void
2960 mono_jit_set_aot_mode (MonoAotMode mode)
2962 /* we don't want to set mono_aot_mode twice */
2963 static gboolean inited;
2965 g_assert (!inited);
2966 mono_aot_mode = mode;
2967 inited = TRUE;
2969 mono_runtime_set_execution_mode (mode);
2972 mono_bool
2973 mono_jit_aot_compiling (void)
2975 return mono_compile_aot;
2979 * mono_jit_set_trace_options:
2980 * \param options string representing the trace options
2981 * Set the options of the tracing engine. This function can be called before initializing
2982 * the mono runtime. See the --trace mono(1) manpage for the options format.
2984 * \returns TRUE if the options were parsed and set correctly, FALSE otherwise.
2986 gboolean
2987 mono_jit_set_trace_options (const char* options)
2989 MonoCallSpec *trace_opt = mono_trace_set_options (options);
2990 if (trace_opt == NULL)
2991 return FALSE;
2992 mono_jit_trace_calls = trace_opt;
2993 return TRUE;
2997 * mono_set_signal_chaining:
2999 * Enable/disable signal chaining. This should be called before \c mono_jit_init.
3000 * If signal chaining is enabled, the runtime saves the original signal handlers before
3001 * installing its own handlers, and calls the original ones in the following cases:
3002 * - a \c SIGSEGV / \c SIGABRT signal received while executing native (i.e. not JITted) code.
3003 * - \c SIGPROF
3004 * - \c SIGFPE
3005 * - \c SIGQUIT
3006 * - \c SIGUSR2
3007 * Signal chaining only works on POSIX platforms.
3009 void
3010 mono_set_signal_chaining (gboolean chain_signals)
3012 mono_do_signal_chaining = chain_signals;
3016 * mono_set_crash_chaining:
3018 * Enable/disable crash chaining due to signals. When a fatal signal is delivered and
3019 * Mono doesn't know how to handle it, it will invoke the crash handler. If chrash chaining
3020 * is enabled, it will first print its crash information and then try to chain with the native handler.
3022 void
3023 mono_set_crash_chaining (gboolean chain_crashes)
3025 mono_do_crash_chaining = chain_crashes;
3029 * mono_parse_options_from:
3030 * \param options string containing strings
3031 * \param ref_argc pointer to the \c argc variable that might be updated
3032 * \param ref_argv pointer to the \c argv string vector variable that might be updated
3034 * This function parses the contents of the \c MONO_ENV_OPTIONS
3035 * environment variable as if they were parsed by a command shell
3036 * splitting the contents by spaces into different elements of the
3037 * \p argv vector. This method supports quoting with both the " and '
3038 * characters. Inside quoting, spaces and tabs are significant,
3039 * otherwise, they are considered argument separators.
3041 * The \ character can be used to escape the next character which will
3042 * be added to the current element verbatim. Typically this is used
3043 * inside quotes. If the quotes are not balanced, this method
3045 * If the environment variable is empty, no changes are made
3046 * to the values pointed by \p ref_argc and \p ref_argv.
3048 * Otherwise the \p ref_argv is modified to point to a new array that contains
3049 * all the previous elements contained in the vector, plus the values parsed.
3050 * The \p argc is updated to match the new number of parameters.
3052 * \returns The value NULL is returned on success, otherwise a \c g_strdup allocated
3053 * string is returned (this is an alias to \c malloc under normal circumstances) that
3054 * contains the error message that happened during parsing.
3056 char *
3057 mono_parse_options_from (const char *options, int *ref_argc, char **ref_argv [])
3059 return mono_parse_options (options, ref_argc, ref_argv, TRUE);
3062 static void
3063 merge_parsed_options (GPtrArray *parsed_options, int *ref_argc, char **ref_argv [], gboolean prepend)
3065 int argc = *ref_argc;
3066 char **argv = *ref_argv;
3068 if (parsed_options->len > 0){
3069 int new_argc = parsed_options->len + argc;
3070 char **new_argv = g_new (char *, new_argc + 1);
3071 guint i;
3072 guint j;
3074 new_argv [0] = argv [0];
3076 i = 1;
3077 if (prepend){
3078 /* First the environment variable settings, to allow the command line options to override */
3079 for (i = 0; i < parsed_options->len; i++)
3080 new_argv [i+1] = (char *)g_ptr_array_index (parsed_options, i);
3081 i++;
3083 for (j = 1; j < argc; j++)
3084 new_argv [i++] = argv [j];
3085 if (!prepend){
3086 for (j = 0; j < parsed_options->len; j++)
3087 new_argv [i++] = (char *)g_ptr_array_index (parsed_options, j);
3089 new_argv [i] = NULL;
3091 *ref_argc = new_argc;
3092 *ref_argv = new_argv;
3096 static char *
3097 mono_parse_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3099 if (options == NULL)
3100 return NULL;
3102 GPtrArray *array = g_ptr_array_new ();
3103 GString *buffer = g_string_new ("");
3104 const char *p;
3105 gboolean in_quotes = FALSE;
3106 char quote_char = '\0';
3108 for (p = options; *p; p++){
3109 switch (*p){
3110 case ' ': case '\t': case '\n':
3111 if (!in_quotes) {
3112 if (buffer->len != 0){
3113 g_ptr_array_add (array, g_strdup (buffer->str));
3114 g_string_truncate (buffer, 0);
3116 } else {
3117 g_string_append_c (buffer, *p);
3119 break;
3120 case '\\':
3121 if (p [1]){
3122 g_string_append_c (buffer, p [1]);
3123 p++;
3125 break;
3126 case '\'':
3127 case '"':
3128 if (in_quotes) {
3129 if (quote_char == *p)
3130 in_quotes = FALSE;
3131 else
3132 g_string_append_c (buffer, *p);
3133 } else {
3134 in_quotes = TRUE;
3135 quote_char = *p;
3137 break;
3138 default:
3139 g_string_append_c (buffer, *p);
3140 break;
3143 if (in_quotes)
3144 return g_strdup_printf ("Unmatched quotes in value: [%s]\n", options);
3146 if (buffer->len != 0)
3147 g_ptr_array_add (array, g_strdup (buffer->str));
3148 g_string_free (buffer, TRUE);
3150 merge_parsed_options (array, ref_argc, ref_argv, prepend);
3151 g_ptr_array_free (array, TRUE);
3153 return NULL;
3156 #if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
3157 #include <shellapi.h>
3159 static char *
3160 mono_win32_parse_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3162 int argc;
3163 gunichar2 **argv;
3164 gunichar2 *optionsw;
3166 if (!options)
3167 return NULL;
3169 GPtrArray *array = g_ptr_array_new ();
3170 optionsw = g_utf8_to_utf16 (options, -1, NULL, NULL, NULL);
3171 if (optionsw) {
3172 gunichar2 *p;
3173 gboolean in_quotes = FALSE;
3174 gunichar2 quote_char = L'\0';
3175 for (p = optionsw; *p; p++){
3176 switch (*p){
3177 case L'\n':
3178 if (!in_quotes)
3179 *p = L' ';
3180 break;
3181 case L'\'':
3182 case L'"':
3183 if (in_quotes) {
3184 if (quote_char == *p)
3185 in_quotes = FALSE;
3186 } else {
3187 in_quotes = TRUE;
3188 quote_char = *p;
3190 break;
3194 argv = CommandLineToArgvW (optionsw, &argc);
3195 if (argv) {
3196 for (int i = 0; i < argc; i++)
3197 g_ptr_array_add (array, g_utf16_to_utf8 (argv[i], -1, NULL, NULL, NULL));
3199 LocalFree (argv);
3202 g_free (optionsw);
3205 merge_parsed_options (array, ref_argc, ref_argv, prepend);
3206 g_ptr_array_free (array, TRUE);
3208 return NULL;
3211 static char *
3212 mono_parse_response_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3214 return mono_win32_parse_options (options, ref_argc, ref_argv, prepend);
3216 #else
3217 static char *
3218 mono_parse_response_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3220 return mono_parse_options (options, ref_argc, ref_argv, prepend);
3222 #endif
3225 * mono_parse_env_options:
3226 * \param ref_argc pointer to the \c argc variable that might be updated
3227 * \param ref_argv pointer to the \c argv string vector variable that might be updated
3229 * This function parses the contents of the \c MONO_ENV_OPTIONS
3230 * environment variable as if they were parsed by a command shell
3231 * splitting the contents by spaces into different elements of the
3232 * \p argv vector. This method supports quoting with both the " and '
3233 * characters. Inside quoting, spaces and tabs are significant,
3234 * otherwise, they are considered argument separators.
3236 * The \ character can be used to escape the next character which will
3237 * be added to the current element verbatim. Typically this is used
3238 * inside quotes. If the quotes are not balanced, this method
3240 * If the environment variable is empty, no changes are made
3241 * to the values pointed by \p ref_argc and \p ref_argv.
3243 * Otherwise the \p ref_argv is modified to point to a new array that contains
3244 * all the previous elements contained in the vector, plus the values parsed.
3245 * The \p argc is updated to match the new number of parameters.
3247 * If there is an error parsing, this method will terminate the process by
3248 * calling exit(1).
3250 * An alternative to this method that allows an arbitrary string to be parsed
3251 * and does not exit on error is the `api:mono_parse_options_from`.
3253 void
3254 mono_parse_env_options (int *ref_argc, char **ref_argv [])
3256 char *ret;
3258 char *env_options = g_getenv ("MONO_ENV_OPTIONS");
3259 if (env_options == NULL)
3260 return;
3261 ret = mono_parse_options_from (env_options, ref_argc, ref_argv);
3262 g_free (env_options);
3263 if (ret == NULL)
3264 return;
3265 fprintf (stderr, "%s", ret);
3266 exit (1);