[interp] Enable compile all debug option also on interp (#13570)
[mono-project.git] / mono / mini / driver.c
blob59e8441da798fda68e9de507b9b71bb3431a011e
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 #ifdef HAVE_SIGNAL_H
16 #include <signal.h>
17 #endif
18 #if HAVE_SCHED_SETAFFINITY
19 #include <sched.h>
20 #endif
21 #ifdef HAVE_UNISTD_H
22 #include <unistd.h>
23 #endif
25 #include <mono/metadata/assembly-internals.h>
26 #include <mono/metadata/loader.h>
27 #include <mono/metadata/tabledefs.h>
28 #include <mono/metadata/class.h>
29 #include <mono/metadata/object.h>
30 #include <mono/metadata/exception.h>
31 #include <mono/metadata/opcodes.h>
32 #include <mono/metadata/mono-endian.h>
33 #include <mono/metadata/tokentype.h>
34 #include <mono/metadata/reflection-internals.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/threads.h>
37 #include <mono/metadata/marshal.h>
38 #include <mono/metadata/appdomain.h>
39 #include <mono/metadata/debug-helpers.h>
40 #include <mono/metadata/profiler-private.h>
41 #include <mono/metadata/mono-config.h>
42 #include <mono/metadata/environment.h>
43 #include <mono/metadata/verify.h>
44 #include <mono/metadata/verify-internals.h>
45 #include <mono/metadata/mono-debug.h>
46 #include <mono/metadata/security-manager.h>
47 #include <mono/metadata/security-core-clr.h>
48 #include <mono/metadata/gc-internals.h>
49 #include <mono/metadata/coree.h>
50 #include <mono/metadata/attach.h>
51 #include <mono/metadata/w32process.h>
52 #include "mono/utils/mono-counters.h"
53 #include "mono/utils/mono-hwcap.h"
54 #include "mono/utils/mono-logger-internals.h"
55 #include "mono/metadata/w32handle.h"
56 #include "mono/metadata/callspec.h"
57 #include "mono/metadata/custom-attrs-internals.h"
59 #include "mini.h"
60 #include "jit.h"
61 #include "aot-compiler.h"
62 #include "aot-runtime.h"
63 #include "mini-runtime.h"
64 #include "interp/interp.h"
66 #include <string.h>
67 #include <ctype.h>
68 #include <locale.h>
69 #include "version.h"
70 #include "debugger-agent.h"
71 #if TARGET_OSX
72 # include <sys/resource.h>
73 #endif
75 static FILE *mini_stats_fd;
77 static void mini_usage (void);
78 static void mono_runtime_set_execution_mode (MonoEEMode mode);
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, need_comma;
285 need_comma = 0;
286 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
287 if (flags & (1 << i) && optflag_get_name (i)) {
288 if (need_comma)
289 g_string_append_c (str, ',');
290 g_string_append (str, optflag_get_name (i));
291 need_comma = 1;
294 return g_string_free (str, FALSE);
297 static const guint32
298 opt_sets [] = {
300 MONO_OPT_PEEPHOLE,
301 MONO_OPT_BRANCH,
302 MONO_OPT_CFOLD,
303 MONO_OPT_FCMOV,
304 MONO_OPT_ALIAS_ANALYSIS,
305 #ifdef MONO_ARCH_SIMD_INTRINSICS
306 MONO_OPT_SIMD | MONO_OPT_INTRINS,
307 MONO_OPT_SSE2,
308 MONO_OPT_SIMD | MONO_OPT_SSE2 | MONO_OPT_INTRINS,
309 #endif
310 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS,
311 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS | MONO_OPT_ALIAS_ANALYSIS,
312 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS,
313 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP,
314 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_CFOLD,
315 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE,
316 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_ALIAS_ANALYSIS,
317 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,
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 | MONO_OPT_TAILCALL,
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_SSA,
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_EXCEPTION,
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 | MONO_OPT_CMOV,
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_ABCREM,
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_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 | MONO_OPT_SHARED,
325 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,
326 DEFAULT_OPTIMIZATIONS,
329 typedef int (*TestMethod) (void);
331 #if 0
332 static void
333 domain_dump_native_code (MonoDomain *domain) {
334 // need to poke into the domain, move to metadata/domain.c
335 // need to empty jit_info_table and code_mp
337 #endif
339 static gboolean do_regression_retries;
340 static int regression_test_skip_index;
343 static gboolean
344 method_should_be_regression_tested (MonoMethod *method, gboolean interp)
346 ERROR_DECL (error);
348 if (strncmp (method->name, "test_", 5) != 0)
349 return FALSE;
351 static gboolean filter_method_init = FALSE;
352 static const char *filter_method = NULL;
354 if (!filter_method_init) {
355 filter_method = g_getenv ("REGRESSION_FILTER_METHOD");
356 filter_method_init = TRUE;
359 if (filter_method) {
360 const char *name = filter_method;
362 if ((strchr (name, '.') > name) || strchr (name, ':')) {
363 MonoMethodDesc *desc = mono_method_desc_new (name, TRUE);
364 gboolean res = mono_method_desc_full_match (desc, method);
365 mono_method_desc_free (desc);
366 return res;
367 } else {
368 return strcmp (method->name, name) == 0;
372 MonoCustomAttrInfo* ainfo = mono_custom_attrs_from_method_checked (method, error);
373 mono_error_cleanup (error);
374 if (!ainfo)
375 return TRUE;
377 int j;
378 for (j = 0; j < ainfo->num_attrs; ++j) {
379 MonoCustomAttrEntry *centry = &ainfo->attrs [j];
380 if (centry->ctor == NULL)
381 continue;
383 MonoClass *klass = centry->ctor->klass;
384 if (strcmp (m_class_get_name (klass), "CategoryAttribute") || mono_method_signature_internal (centry->ctor)->param_count != 1)
385 continue;
387 gpointer *typed_args, *named_args;
388 int num_named_args;
389 CattrNamedArg *arginfo;
391 mono_reflection_create_custom_attr_data_args_noalloc (
392 mono_defaults.corlib, centry->ctor, centry->data, centry->data_size,
393 &typed_args, &named_args, &num_named_args, &arginfo, error);
394 if (!is_ok (error))
395 continue;
397 char *utf8_str = (char*)(void*)typed_args[0]; //this points into image memory that is constant
398 g_free (typed_args);
399 g_free (named_args);
400 g_free (arginfo);
402 if (interp && !strcmp (utf8_str, "!INTERPRETER")) {
403 g_print ("skip %s...\n", method->name);
404 return FALSE;
407 #if HOST_WASM
408 if (!strcmp (utf8_str, "!WASM")) {
409 g_print ("skip %s...\n", method->name);
410 return FALSE;
412 #endif
413 if (mono_aot_mode == MONO_AOT_MODE_FULL && !strcmp (utf8_str, "!FULLAOT")) {
414 g_print ("skip %s...\n", method->name);
415 return FALSE;
418 if ((mono_aot_mode == MONO_AOT_MODE_INTERP_LLVMONLY || mono_aot_mode == MONO_AOT_MODE_LLVMONLY) && !strcmp (utf8_str, "!BITCODE")) {
419 g_print ("skip %s...\n", method->name);
420 return FALSE;
424 return TRUE;
427 static void
428 mini_regression_step (MonoImage *image, int verbose, int *total_run, int *total,
429 guint32 opt_flags,
430 GTimer *timer, MonoDomain *domain)
432 int result, expected, failed, cfailed, run, code_size;
433 double elapsed, comp_time, start_time;
434 char *n;
435 int i;
437 mono_set_defaults (verbose, opt_flags);
438 n = mono_opt_descr (opt_flags);
439 g_print ("Test run: image=%s, opts=%s\n", mono_image_get_filename (image), n);
440 g_free (n);
441 cfailed = failed = run = code_size = 0;
442 comp_time = elapsed = 0.0;
443 int local_skip_index = 0;
445 /* fixme: ugly hack - delete all previously compiled methods */
446 if (domain_jit_info (domain)) {
447 g_hash_table_destroy (domain_jit_info (domain)->jit_trampoline_hash);
448 domain_jit_info (domain)->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
449 mono_internal_hash_table_destroy (&(domain->jit_code_hash));
450 mono_jit_code_hash_init (&(domain->jit_code_hash));
453 g_timer_start (timer);
454 if (mini_stats_fd)
455 fprintf (mini_stats_fd, "[");
456 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
457 ERROR_DECL (error);
458 MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
459 if (!method) {
460 mono_error_cleanup (error); /* FIXME don't swallow the error */
461 continue;
463 if (method_should_be_regression_tested (method, FALSE)) {
464 MonoCompile *cfg = NULL;
465 TestMethod func = NULL;
467 expected = atoi (method->name + 5);
468 run++;
469 start_time = g_timer_elapsed (timer, NULL);
471 #ifdef DISABLE_JIT
472 #ifdef MONO_USE_AOT_COMPILER
473 ERROR_DECL (error);
474 func = (TestMethod)mono_aot_get_method (mono_get_root_domain (), method, error);
475 mono_error_cleanup (error);
476 #else
477 g_error ("No JIT or AOT available, regression testing not possible!")
478 #endif
480 #else
481 comp_time -= start_time;
482 cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, opt_flags), mono_get_root_domain (), JIT_FLAG_RUN_CCTORS, 0, -1);
483 comp_time += g_timer_elapsed (timer, NULL);
484 if (cfg->exception_type == MONO_EXCEPTION_NONE) {
485 #ifdef MONO_USE_AOT_COMPILER
486 ERROR_DECL (error);
487 func = (TestMethod)mono_aot_get_method (mono_get_root_domain (), method, error);
488 mono_error_cleanup (error);
489 if (!func)
490 func = (TestMethod)(gpointer)cfg->native_code;
491 #else
492 func = (TestMethod)(gpointer)cfg->native_code;
493 #endif
494 func = (TestMethod)mono_create_ftnptr (mono_get_root_domain (), (gpointer)func);
496 #endif
498 if (func) {
499 if (do_regression_retries) {
500 ++local_skip_index;
502 if(local_skip_index <= regression_test_skip_index)
503 continue;
504 ++regression_test_skip_index;
507 if (verbose >= 2)
508 g_print ("Running '%s' ...\n", method->name);
510 #if HOST_WASM
511 //WASM AOT injects dummy args and we must call with exact signatures
512 int (*func_2)(int) = (int (*)(int))(void*)func;
513 result = func_2 (-1);
514 #else
515 result = func ();
516 #endif
517 if (result != expected) {
518 failed++;
519 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
521 if (cfg) {
522 code_size += cfg->code_len;
523 mono_destroy_compile (cfg);
525 } else {
526 cfailed++;
527 g_print ("Test '%s' failed compilation.\n", method->name);
529 if (mini_stats_fd)
530 fprintf (mini_stats_fd, "%f, ",
531 g_timer_elapsed (timer, NULL) - start_time);
534 if (mini_stats_fd)
535 fprintf (mini_stats_fd, "],\n");
536 g_timer_stop (timer);
537 elapsed = g_timer_elapsed (timer, NULL);
538 if (failed > 0 || cfailed > 0){
539 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n",
540 run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
541 } else {
542 g_print ("Results: total tests: %d, all pass \n", run);
545 g_print ("Elapsed time: %f secs (%f, %f), Code size: %d\n\n", elapsed,
546 elapsed - comp_time, comp_time, code_size);
547 *total += failed + cfailed;
548 *total_run += run;
551 static int
552 mini_regression (MonoImage *image, int verbose, int *total_run)
554 guint32 i, opt;
555 MonoMethod *method;
556 char *n;
557 GTimer *timer = g_timer_new ();
558 MonoDomain *domain = mono_domain_get ();
559 guint32 exclude = 0;
560 int total;
562 /* Note: mono_hwcap_init () called in mono_init () before we get here. */
563 mono_arch_cpu_optimizations (&exclude);
565 if (mini_stats_fd) {
566 fprintf (mini_stats_fd, "$stattitle = \'Mono Benchmark Results (various optimizations)\';\n");
568 fprintf (mini_stats_fd, "$graph->set_legend(qw(");
569 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); opt++) {
570 guint32 opt_flags = opt_sets [opt];
571 n = mono_opt_descr (opt_flags);
572 if (!n [0])
573 n = (char *)"none";
574 if (opt)
575 fprintf (mini_stats_fd, " ");
576 fprintf (mini_stats_fd, "%s", n);
580 fprintf (mini_stats_fd, "));\n");
582 fprintf (mini_stats_fd, "@data = (\n");
583 fprintf (mini_stats_fd, "[");
586 /* load the metadata */
587 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
588 ERROR_DECL (error);
589 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
590 if (!method) {
591 mono_error_cleanup (error);
592 continue;
594 mono_class_init_internal (method->klass);
596 if (!strncmp (method->name, "test_", 5) && mini_stats_fd) {
597 fprintf (mini_stats_fd, "\"%s\",", method->name);
600 if (mini_stats_fd)
601 fprintf (mini_stats_fd, "],\n");
604 total = 0;
605 *total_run = 0;
606 if (mono_do_single_method_regression) {
607 GSList *iter;
609 mini_regression_step (image, verbose, total_run, &total,
611 timer, domain);
612 if (total)
613 return total;
614 g_print ("Single method regression: %d methods\n", g_slist_length (mono_single_method_list));
616 for (iter = mono_single_method_list; iter; iter = g_slist_next (iter)) {
617 char *method_name;
619 mono_current_single_method = (MonoMethod *)iter->data;
621 method_name = mono_method_full_name (mono_current_single_method, TRUE);
622 g_print ("Current single method: %s\n", method_name);
623 g_free (method_name);
625 mini_regression_step (image, verbose, total_run, &total,
627 timer, domain);
628 if (total)
629 return total;
631 } else {
632 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); ++opt) {
633 /* builtin-types.cs & aot-tests.cs need OPT_INTRINS enabled */
634 if (!strcmp ("builtin-types", image->assembly_name) || !strcmp ("aot-tests", image->assembly_name))
635 if (!(opt_sets [opt] & MONO_OPT_INTRINS))
636 continue;
638 //we running in AOT only, it makes no sense to try multiple flags
639 if ((mono_aot_mode == MONO_AOT_MODE_FULL || mono_aot_mode == MONO_AOT_MODE_LLVMONLY) && opt_sets [opt] != DEFAULT_OPTIMIZATIONS) {
640 continue;
643 mini_regression_step (image, verbose, total_run, &total,
644 opt_sets [opt] & ~exclude,
645 timer, domain);
649 if (mini_stats_fd) {
650 fprintf (mini_stats_fd, ");\n");
651 fflush (mini_stats_fd);
654 g_timer_destroy (timer);
655 return total;
658 static int
659 mini_regression_list (int verbose, int count, char *images [])
661 int i, total, total_run, run;
662 MonoAssembly *ass;
664 total_run = total = 0;
665 for (i = 0; i < count; ++i) {
666 MonoAssemblyOpenRequest req;
667 mono_assembly_request_prepare (&req.request, sizeof (req), MONO_ASMCTX_DEFAULT);
668 ass = mono_assembly_request_open (images [i], &req, NULL);
669 if (!ass) {
670 g_warning ("failed to load assembly: %s", images [i]);
671 continue;
673 total += mini_regression (mono_assembly_get_image_internal (ass), verbose, &run);
674 total_run += run;
676 if (total > 0){
677 g_print ("Overall results: tests: %d, failed: %d, opt combinations: %d (pass: %.2f%%)\n",
678 total_run, total, (int)G_N_ELEMENTS (opt_sets), 100.0*(total_run-total)/total_run);
679 } else {
680 g_print ("Overall results: tests: %d, 100%% pass, opt combinations: %d\n",
681 total_run, (int)G_N_ELEMENTS (opt_sets));
684 return total;
687 static void
688 interp_regression_step (MonoImage *image, int verbose, int *total_run, int *total, GTimer *timer, MonoDomain *domain)
690 int result, expected, failed, cfailed, run;
691 double elapsed, transform_time;
692 int i;
693 MonoObject *result_obj;
694 int local_skip_index = 0;
696 g_print ("Test run: image=%s\n", mono_image_get_filename (image));
697 cfailed = failed = run = 0;
698 transform_time = elapsed = 0.0;
700 g_timer_start (timer);
701 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
702 ERROR_DECL (error);
703 MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
704 if (!method) {
705 mono_error_cleanup (error); /* FIXME don't swallow the error */
706 continue;
709 if (method_should_be_regression_tested (method, TRUE)) {
710 ERROR_DECL (interp_error);
711 MonoObject *exc = NULL;
713 if (do_regression_retries) {
714 ++local_skip_index;
716 if(local_skip_index <= regression_test_skip_index)
717 continue;
718 ++regression_test_skip_index;
721 result_obj = mini_get_interp_callbacks ()->runtime_invoke (method, NULL, NULL, &exc, interp_error);
722 if (!mono_error_ok (interp_error)) {
723 cfailed++;
724 g_print ("Test '%s' execution failed.\n", method->name);
725 } else if (exc != NULL) {
726 g_print ("Exception in Test '%s' occured:\n", method->name);
727 mono_object_describe (exc);
728 run++;
729 failed++;
730 } else {
731 result = *(gint32 *) mono_object_unbox_internal (result_obj);
732 expected = atoi (method->name + 5); // FIXME: oh no.
733 run++;
735 if (result != expected) {
736 failed++;
737 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
742 g_timer_stop (timer);
743 elapsed = g_timer_elapsed (timer, NULL);
744 if (failed > 0 || cfailed > 0){
745 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n",
746 run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
747 } else {
748 g_print ("Results: total tests: %d, all pass \n", run);
751 g_print ("Elapsed time: %f secs (%f, %f)\n\n", elapsed,
752 elapsed - transform_time, transform_time);
753 *total += failed + cfailed;
754 *total_run += run;
757 static int
758 interp_regression (MonoImage *image, int verbose, int *total_run)
760 MonoMethod *method;
761 GTimer *timer = g_timer_new ();
762 MonoDomain *domain = mono_domain_get ();
763 guint32 i;
764 int total;
766 /* load the metadata */
767 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
768 ERROR_DECL (error);
769 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
770 if (!method) {
771 mono_error_cleanup (error);
772 continue;
774 mono_class_init_internal (method->klass);
777 total = 0;
778 *total_run = 0;
779 interp_regression_step (image, verbose, total_run, &total, timer, domain);
781 g_timer_destroy (timer);
782 return total;
785 /* TODO: merge this code with the regression harness of the JIT */
786 static int
787 mono_interp_regression_list (int verbose, int count, char *images [])
789 int i, total, total_run, run;
791 total_run = total = 0;
792 for (i = 0; i < count; ++i) {
793 MonoAssemblyOpenRequest req;
794 mono_assembly_request_prepare (&req.request, sizeof (req), MONO_ASMCTX_DEFAULT);
795 MonoAssembly *ass = mono_assembly_request_open (images [i], &req, NULL);
796 if (!ass) {
797 g_warning ("failed to load assembly: %s", images [i]);
798 continue;
800 total += interp_regression (mono_assembly_get_image_internal (ass), verbose, &run);
801 total_run += run;
803 if (total > 0) {
804 g_print ("Overall results: tests: %d, failed: %d (pass: %.2f%%)\n", total_run, total, 100.0*(total_run-total)/total_run);
805 } else {
806 g_print ("Overall results: tests: %d, 100%% pass\n", total_run);
809 return total;
813 #ifdef MONO_JIT_INFO_TABLE_TEST
814 typedef struct _JitInfoData
816 guint start;
817 guint length;
818 MonoJitInfo *ji;
819 struct _JitInfoData *next;
820 } JitInfoData;
822 typedef struct
824 guint start;
825 guint length;
826 int num_datas;
827 JitInfoData *data;
828 } Region;
830 typedef struct
832 int num_datas;
833 int num_regions;
834 Region *regions;
835 int num_frees;
836 JitInfoData *frees;
837 } ThreadData;
839 static int num_threads;
840 static ThreadData *thread_datas;
841 static MonoDomain *test_domain;
843 static JitInfoData*
844 alloc_random_data (Region *region)
846 JitInfoData **data;
847 JitInfoData *prev;
848 guint prev_end;
849 guint next_start;
850 guint max_len;
851 JitInfoData *d;
852 int num_retries = 0;
853 int pos, i;
855 restart:
856 prev = NULL;
857 data = &region->data;
858 pos = random () % (region->num_datas + 1);
859 i = 0;
860 while (*data != NULL) {
861 if (i++ == pos)
862 break;
863 prev = *data;
864 data = &(*data)->next;
867 if (prev == NULL)
868 g_assert (*data == region->data);
869 else
870 g_assert (prev->next == *data);
872 if (prev == NULL)
873 prev_end = region->start;
874 else
875 prev_end = prev->start + prev->length;
877 if (*data == NULL)
878 next_start = region->start + region->length;
879 else
880 next_start = (*data)->start;
882 g_assert (prev_end <= next_start);
884 max_len = next_start - prev_end;
885 if (max_len < 128) {
886 if (++num_retries >= 10)
887 return NULL;
888 goto restart;
890 if (max_len > 1024)
891 max_len = 1024;
893 d = g_new0 (JitInfoData, 1);
894 d->start = prev_end + random () % (max_len / 2);
895 d->length = random () % MIN (max_len, next_start - d->start) + 1;
897 g_assert (d->start >= prev_end && d->start + d->length <= next_start);
899 d->ji = g_new0 (MonoJitInfo, 1);
900 d->ji->d.method = (MonoMethod*) 0xABadBabe;
901 d->ji->code_start = (gpointer)(gulong) d->start;
902 d->ji->code_size = d->length;
903 d->ji->cas_inited = 1; /* marks an allocated jit info */
905 d->next = *data;
906 *data = d;
908 ++region->num_datas;
910 return d;
913 static JitInfoData**
914 choose_random_data (Region *region)
916 int n;
917 int i;
918 JitInfoData **d;
920 g_assert (region->num_datas > 0);
922 n = random () % region->num_datas;
924 for (d = &region->data, i = 0;
925 i < n;
926 d = &(*d)->next, ++i)
929 return d;
932 static Region*
933 choose_random_region (ThreadData *td)
935 return &td->regions [random () % td->num_regions];
938 static ThreadData*
939 choose_random_thread (void)
941 return &thread_datas [random () % num_threads];
944 static void
945 free_jit_info_data (ThreadData *td, JitInfoData *free)
947 free->next = td->frees;
948 td->frees = free;
950 if (++td->num_frees >= 1000) {
951 int i;
953 for (i = 0; i < 500; ++i)
954 free = free->next;
956 while (free->next != NULL) {
957 JitInfoData *next = free->next->next;
959 //g_free (free->next->ji);
960 g_free (free->next);
961 free->next = next;
963 --td->num_frees;
968 #define NUM_THREADS 8
969 #define REGIONS_PER_THREAD 10
970 #define REGION_SIZE 0x10000
972 #define MAX_ADDR (REGION_SIZE * REGIONS_PER_THREAD * NUM_THREADS)
974 #define MODE_ALLOC 1
975 #define MODE_FREE 2
977 static void
978 test_thread_func (gpointer void_arg)
980 ThreadData* td = (ThreadData*)void_arg;
981 int mode = MODE_ALLOC;
982 int i = 0;
983 gulong lookup_successes = 0, lookup_failures = 0;
984 MonoDomain *domain = test_domain;
985 int thread_num = (int)(td - thread_datas);
986 gboolean modify_thread = thread_num < NUM_THREADS / 2; /* only half of the threads modify the table */
988 for (;;) {
989 int alloc;
990 int lookup = 1;
992 if (td->num_datas == 0) {
993 lookup = 0;
994 alloc = 1;
995 } else if (modify_thread && random () % 1000 < 5) {
996 lookup = 0;
997 if (mode == MODE_ALLOC)
998 alloc = (random () % 100) < 70;
999 else if (mode == MODE_FREE)
1000 alloc = (random () % 100) < 30;
1003 if (lookup) {
1004 /* modify threads sometimes look up their own jit infos */
1005 if (modify_thread && random () % 10 < 5) {
1006 Region *region = choose_random_region (td);
1008 if (region->num_datas > 0) {
1009 JitInfoData **data = choose_random_data (region);
1010 guint pos = (*data)->start + random () % (*data)->length;
1011 MonoJitInfo *ji;
1013 ji = mono_jit_info_table_find (domain, (char*)(gsize)pos);
1015 g_assert (ji->cas_inited);
1016 g_assert ((*data)->ji == ji);
1018 } else {
1019 int pos = random () % MAX_ADDR;
1020 char *addr = (char*)(uintptr_t)pos;
1021 MonoJitInfo *ji;
1023 ji = mono_jit_info_table_find (domain, addr);
1026 * FIXME: We are actually not allowed
1027 * to do this. By the time we examine
1028 * the ji another thread might already
1029 * have removed it.
1031 if (ji != NULL) {
1032 g_assert (addr >= (char*)ji->code_start && addr < (char*)ji->code_start + ji->code_size);
1033 ++lookup_successes;
1034 } else
1035 ++lookup_failures;
1037 } else if (alloc) {
1038 JitInfoData *data = alloc_random_data (choose_random_region (td));
1040 if (data != NULL) {
1041 mono_jit_info_table_add (domain, data->ji);
1043 ++td->num_datas;
1045 } else {
1046 Region *region = choose_random_region (td);
1048 if (region->num_datas > 0) {
1049 JitInfoData **data = choose_random_data (region);
1050 JitInfoData *free;
1052 mono_jit_info_table_remove (domain, (*data)->ji);
1054 //(*data)->ji->cas_inited = 0; /* marks a free jit info */
1056 free = *data;
1057 *data = (*data)->next;
1059 free_jit_info_data (td, free);
1061 --region->num_datas;
1062 --td->num_datas;
1066 if (++i % 100000 == 0) {
1067 int j;
1068 g_print ("num datas %d (%ld - %ld): %d", (int)(td - thread_datas),
1069 lookup_successes, lookup_failures, td->num_datas);
1070 for (j = 0; j < td->num_regions; ++j)
1071 g_print (" %d", td->regions [j].num_datas);
1072 g_print ("\n");
1075 if (td->num_datas < 100)
1076 mode = MODE_ALLOC;
1077 else if (td->num_datas > 2000)
1078 mode = MODE_FREE;
1083 static void
1084 small_id_thread_func (gpointer arg)
1086 MonoThread *thread = mono_thread_current ();
1087 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1089 g_print ("my small id is %d\n", (int)thread->small_id);
1090 mono_hazard_pointer_clear (hp, 1);
1091 sleep (3);
1092 g_print ("done %d\n", (int)thread->small_id);
1096 static void
1097 jit_info_table_test (MonoDomain *domain)
1099 ERROR_DECL (error);
1100 int i;
1102 g_print ("testing jit_info_table\n");
1104 num_threads = NUM_THREADS;
1105 thread_datas = g_new0 (ThreadData, num_threads);
1107 for (i = 0; i < num_threads; ++i) {
1108 int j;
1110 thread_datas [i].num_regions = REGIONS_PER_THREAD;
1111 thread_datas [i].regions = g_new0 (Region, REGIONS_PER_THREAD);
1113 for (j = 0; j < REGIONS_PER_THREAD; ++j) {
1114 thread_datas [i].regions [j].start = (num_threads * j + i) * REGION_SIZE;
1115 thread_datas [i].regions [j].length = REGION_SIZE;
1119 test_domain = domain;
1122 for (i = 0; i < 72; ++i)
1123 mono_thread_create (domain, small_id_thread_func, NULL);
1125 sleep (2);
1128 for (i = 0; i < num_threads; ++i) {
1129 mono_thread_create_checked (domain, (gpointer)test_thread_func, &thread_datas [i], error);
1130 mono_error_assert_ok (error);
1133 #endif
1135 enum {
1136 DO_BENCH,
1137 DO_REGRESSION,
1138 DO_SINGLE_METHOD_REGRESSION,
1139 DO_COMPILE,
1140 DO_EXEC,
1141 DO_DRAW,
1142 DO_DEBUGGER
1145 typedef struct CompileAllThreadArgs {
1146 MonoAssembly *ass;
1147 int verbose;
1148 guint32 opts;
1149 guint32 recompilation_times;
1150 } CompileAllThreadArgs;
1152 static void
1153 compile_all_methods_thread_main_inner (CompileAllThreadArgs *args)
1155 MonoAssembly *ass = args->ass;
1156 int verbose = args->verbose;
1157 MonoImage *image = mono_assembly_get_image_internal (ass);
1158 MonoMethod *method;
1159 MonoCompile *cfg;
1160 int i, count = 0, fail_count = 0;
1162 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
1163 ERROR_DECL (error);
1164 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1165 MonoMethodSignature *sig;
1167 if (mono_metadata_has_generic_params (image, token))
1168 continue;
1170 method = mono_get_method_checked (image, token, NULL, NULL, error);
1171 if (!method) {
1172 mono_error_cleanup (error); /* FIXME don't swallow the error */
1173 continue;
1175 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1176 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1177 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1178 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1179 continue;
1181 if (mono_class_is_gtd (method->klass))
1182 continue;
1183 sig = mono_method_signature_internal (method);
1184 if (!sig) {
1185 char * desc = mono_method_full_name (method, TRUE);
1186 g_print ("Could not retrieve method signature for %s\n", desc);
1187 g_free (desc);
1188 fail_count ++;
1189 continue;
1192 if (sig->has_type_parameters)
1193 continue;
1195 count++;
1196 if (verbose) {
1197 char * desc = mono_method_full_name (method, TRUE);
1198 g_print ("Compiling %d %s\n", count, desc);
1199 g_free (desc);
1201 if (mono_use_interpreter) {
1202 mini_get_interp_callbacks ()->create_method_pointer (method, TRUE, error);
1203 // FIXME There are a few failures due to DllNotFoundException related to System.Native
1204 if (verbose && !mono_error_ok (error))
1205 g_print ("Compilation of %s failed\n", mono_method_full_name (method, TRUE));
1206 } else {
1207 cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, args->opts), mono_get_root_domain (), (JitFlags)JIT_FLAG_DISCARD_RESULTS, 0, -1);
1208 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
1209 const char *msg = cfg->exception_message;
1210 if (cfg->exception_type == MONO_EXCEPTION_MONO_ERROR)
1211 msg = mono_error_get_message (&cfg->error);
1212 g_print ("Compilation of %s failed with exception '%s':\n", mono_method_full_name (cfg->method, TRUE), msg);
1213 fail_count ++;
1215 mono_destroy_compile (cfg);
1219 if (fail_count)
1220 exit (1);
1223 static void
1224 compile_all_methods_thread_main (gpointer void_args)
1226 CompileAllThreadArgs *args = (CompileAllThreadArgs*)void_args;
1227 guint32 i;
1228 for (i = 0; i < args->recompilation_times; ++i)
1229 compile_all_methods_thread_main_inner (args);
1232 static void
1233 compile_all_methods (MonoAssembly *ass, int verbose, guint32 opts, guint32 recompilation_times)
1235 ERROR_DECL (error);
1236 CompileAllThreadArgs args;
1238 args.ass = ass;
1239 args.verbose = verbose;
1240 args.opts = opts;
1241 args.recompilation_times = recompilation_times;
1244 * Need to create a mono thread since compilation might trigger
1245 * running of managed code.
1247 mono_thread_create_checked (mono_domain_get (), (gpointer)compile_all_methods_thread_main, &args, error);
1248 mono_error_assert_ok (error);
1250 mono_thread_manage ();
1254 * mono_jit_exec:
1255 * \param assembly reference to an assembly
1256 * \param argc argument count
1257 * \param argv argument vector
1258 * Start execution of a program.
1260 int
1261 mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
1263 int rv;
1264 MONO_ENTER_GC_UNSAFE;
1265 rv = mono_jit_exec_internal (domain, assembly, argc, argv);
1266 MONO_EXIT_GC_UNSAFE;
1267 return rv;
1271 mono_jit_exec_internal (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
1273 MONO_REQ_GC_UNSAFE_MODE;
1274 ERROR_DECL (error);
1275 MonoImage *image = mono_assembly_get_image_internal (assembly);
1277 // We need to ensure that any module cctor for this image
1278 // is run *before* we invoke the entry point
1279 // For more information, see https://blogs.msdn.microsoft.com/junfeng/2005/11/19/module-initializer-a-k-a-module-constructor/
1281 // This is required in order for tools like Costura
1282 // (https://github.com/Fody/Costura) to work properly, as they inject
1283 // a module initializer which sets up event handlers (e.g. AssemblyResolve)
1284 // that allow the main method to run properly
1285 if (!mono_runtime_run_module_cctor(image, domain, error)) {
1286 g_print ("Failed to run module constructor due to %s\n", mono_error_get_message (error));
1287 return 1;
1290 MonoMethod *method;
1291 guint32 entry = mono_image_get_entry_point (image);
1293 if (!entry) {
1294 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
1295 /* FIXME: remove this silly requirement. */
1296 mono_environment_exitcode_set (1);
1297 return 1;
1300 method = mono_get_method_checked (image, entry, NULL, NULL, error);
1301 if (method == NULL){
1302 g_print ("The entry point method could not be loaded due to %s\n", mono_error_get_message (error));
1303 mono_error_cleanup (error);
1304 mono_environment_exitcode_set (1);
1305 return 1;
1308 if (mono_llvm_only) {
1309 MonoObject *exc = NULL;
1310 int res;
1312 res = mono_runtime_try_run_main (method, argc, argv, &exc);
1313 if (exc) {
1314 mono_unhandled_exception_internal (exc);
1315 mono_invoke_unhandled_exception_hook (exc);
1316 g_assert_not_reached ();
1318 return res;
1319 } else {
1320 int res = mono_runtime_run_main_checked (method, argc, argv, error);
1321 if (!is_ok (error)) {
1322 MonoException *ex = mono_error_convert_to_exception (error);
1323 if (ex) {
1324 mono_unhandled_exception_internal (&ex->object);
1325 mono_invoke_unhandled_exception_hook (&ex->object);
1326 g_assert_not_reached ();
1329 return res;
1333 typedef struct
1335 MonoDomain *domain;
1336 const char *file;
1337 int argc;
1338 char **argv;
1339 guint32 opts;
1340 char *aot_options;
1341 } MainThreadArgs;
1343 static void main_thread_handler (gpointer user_data)
1345 MainThreadArgs *main_args = (MainThreadArgs *)user_data;
1346 MonoAssembly *assembly;
1348 if (mono_compile_aot) {
1349 int i, res;
1350 gpointer *aot_state = NULL;
1352 /* Treat the other arguments as assemblies to compile too */
1353 for (i = 0; i < main_args->argc; ++i) {
1354 assembly = mono_domain_assembly_open (main_args->domain, main_args->argv [i]);
1355 if (!assembly) {
1356 fprintf (stderr, "Can not open image %s\n", main_args->argv [i]);
1357 exit (1);
1359 /* Check that the assembly loaded matches the filename */
1361 MonoImageOpenStatus status;
1362 MonoImage *img;
1364 img = mono_image_open (main_args->argv [i], &status);
1365 if (img && strcmp (img->name, assembly->image->name)) {
1366 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);
1367 exit (1);
1370 res = mono_compile_assembly (assembly, main_args->opts, main_args->aot_options, &aot_state);
1371 if (res != 0) {
1372 fprintf (stderr, "AOT of image %s failed.\n", main_args->argv [i]);
1373 exit (1);
1376 if (aot_state) {
1377 res = mono_compile_deferred_assemblies (main_args->opts, main_args->aot_options, &aot_state);
1378 if (res != 0) {
1379 fprintf (stderr, "AOT of mode-specific deferred assemblies failed.\n");
1380 exit (1);
1383 } else {
1384 assembly = mono_domain_assembly_open (main_args->domain, main_args->file);
1385 if (!assembly){
1386 fprintf (stderr, "Can not open image %s\n", main_args->file);
1387 exit (1);
1391 * This must be done in a thread managed by mono since it can invoke
1392 * managed code.
1394 if (main_args->opts & MONO_OPT_PRECOMP)
1395 mono_precompile_assemblies ();
1397 mono_jit_exec (main_args->domain, assembly, main_args->argc, main_args->argv);
1401 static int
1402 load_agent (MonoDomain *domain, char *desc)
1404 ERROR_DECL (error);
1405 char* col = strchr (desc, ':');
1406 char *agent, *args;
1407 MonoAssembly *agent_assembly;
1408 MonoImage *image;
1409 MonoMethod *method;
1410 guint32 entry;
1411 MonoArray *main_args;
1412 gpointer pa [1];
1413 MonoImageOpenStatus open_status;
1415 if (col) {
1416 agent = (char *)g_memdup (desc, col - desc + 1);
1417 agent [col - desc] = '\0';
1418 args = col + 1;
1419 } else {
1420 agent = g_strdup (desc);
1421 args = NULL;
1424 MonoAssemblyOpenRequest req;
1425 mono_assembly_request_prepare (&req.request, sizeof (req), MONO_ASMCTX_DEFAULT);
1426 agent_assembly = mono_assembly_request_open (agent, &req, &open_status);
1427 if (!agent_assembly) {
1428 fprintf (stderr, "Cannot open agent assembly '%s': %s.\n", agent, mono_image_strerror (open_status));
1429 g_free (agent);
1430 return 2;
1434 * Can't use mono_jit_exec (), as it sets things which might confuse the
1435 * real Main method.
1437 image = mono_assembly_get_image_internal (agent_assembly);
1438 entry = mono_image_get_entry_point (image);
1439 if (!entry) {
1440 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
1441 g_free (agent);
1442 return 1;
1445 method = mono_get_method_checked (image, entry, NULL, NULL, error);
1446 if (method == NULL){
1447 g_print ("The entry point method of assembly '%s' could not be loaded due to %s\n", agent, mono_error_get_message (error));
1448 mono_error_cleanup (error);
1449 g_free (agent);
1450 return 1;
1453 mono_thread_set_main (mono_thread_current ());
1455 if (args) {
1456 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 1, error);
1457 if (main_args) {
1458 MonoString *str = mono_string_new_checked (domain, args, error);
1459 if (str)
1460 mono_array_set_internal (main_args, MonoString*, 0, str);
1462 } else {
1463 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 0, error);
1465 if (!main_args) {
1466 g_print ("Could not allocate array for main args of assembly '%s' due to %s\n", agent, mono_error_get_message (error));
1467 mono_error_cleanup (error);
1468 g_free (agent);
1469 return 1;
1473 pa [0] = main_args;
1474 /* Pass NULL as 'exc' so unhandled exceptions abort the runtime */
1475 mono_runtime_invoke_checked (method, NULL, pa, error);
1476 if (!is_ok (error)) {
1477 g_print ("The entry point method of assembly '%s' could not execute due to %s\n", agent, mono_error_get_message (error));
1478 mono_error_cleanup (error);
1479 g_free (agent);
1480 return 1;
1483 g_free (agent);
1484 return 0;
1487 static void
1488 mini_usage_jitdeveloper (void)
1490 int i;
1492 fprintf (stdout,
1493 "Runtime and JIT debugging options:\n"
1494 " --apply-bindings=FILE Apply assembly bindings from FILE (only for AOT)\n"
1495 " --breakonex Inserts a breakpoint on exceptions\n"
1496 " --break METHOD Inserts a breakpoint at METHOD entry\n"
1497 " --break-at-bb METHOD N Inserts a breakpoint in METHOD at BB N\n"
1498 " --compile METHOD Just compile METHOD in assembly\n"
1499 " --compile-all=N Compiles all the methods in the assembly multiple times (default: 1)\n"
1500 " --ncompile N Number of times to compile METHOD (default: 1)\n"
1501 " --print-vtable Print the vtable of all used classes\n"
1502 " --regression Runs the regression test contained in the assembly\n"
1503 " --single-method=OPTS Runs regressions with only one method optimized with OPTS at any time\n"
1504 " --statfile FILE Sets the stat file to FILE\n"
1505 " --stats Print statistics about the JIT operations\n"
1506 " --inject-async-exc METHOD OFFSET Inject an asynchronous exception at METHOD\n"
1507 " --verify-all Run the verifier on all assemblies and methods\n"
1508 " --full-aot Avoid JITting any code\n"
1509 " --llvmonly Use LLVM compiled code only\n"
1510 " --agent=ASSEMBLY[:ARG] Loads the specific agent assembly and executes its Main method with the given argument before loading the main assembly.\n"
1511 " --no-x86-stack-align Don't align stack on x86\n"
1512 "\n"
1513 "The options supported by MONO_DEBUG can also be passed on the command line.\n"
1514 "\n"
1515 "Other options:\n"
1516 " --graph[=TYPE] METHOD Draws a graph of the specified method:\n");
1518 for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
1519 fprintf (stdout, " %-10s %s\n", graph_names [i].name, graph_names [i].desc);
1523 static void
1524 mini_usage_list_opt (void)
1526 int i;
1528 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i)
1529 fprintf (stdout, " %-10s %s\n", optflag_get_name (i), optflag_get_desc (i));
1532 static void
1533 mini_usage (void)
1535 fprintf (stdout,
1536 "Usage is: mono [options] program [program-options]\n"
1537 "\n"
1538 "Development:\n"
1539 " --aot[=<options>] Compiles the assembly to native code\n"
1540 " --debug[=<options>] Enable debugging support, use --help-debug for details\n"
1541 " --debugger-agent=options Enable the debugger agent\n"
1542 " --profile[=profiler] Runs in profiling mode with the specified profiler module\n"
1543 " --trace[=EXPR] Enable tracing, use --help-trace for details\n"
1544 " --jitmap Output a jit method map to /tmp/perf-PID.map\n"
1545 " --help-devel Shows more options available to developers\n"
1546 "\n"
1547 "Runtime:\n"
1548 " --config FILE Loads FILE as the Mono config\n"
1549 " --verbose, -v Increases the verbosity level\n"
1550 " --help, -h Show usage information\n"
1551 " --version, -V Show version information\n"
1552 " --runtime=VERSION Use the VERSION runtime, instead of autodetecting\n"
1553 " --optimize=OPT Turns on or off a specific optimization\n"
1554 " Use --list-opt to get a list of optimizations\n"
1555 " --attach=OPTIONS Pass OPTIONS to the attach agent in the runtime.\n"
1556 " Currently the only supported option is 'disable'.\n"
1557 " --llvm, --nollvm Controls whenever the runtime uses LLVM to compile code.\n"
1558 " --gc=[sgen,boehm] Select SGen or Boehm GC (runs mono or mono-sgen)\n"
1559 #ifdef TARGET_OSX
1560 " --arch=[32,64] Select architecture (runs mono32 or mono64)\n"
1561 #endif
1562 #ifdef HOST_WIN32
1563 " --mixed-mode Enable mixed-mode image support.\n"
1564 #endif
1565 " --handlers Install custom handlers, use --help-handlers for details.\n"
1566 " --aot-path=PATH List of additional directories to search for AOT images.\n"
1570 static void
1571 mini_trace_usage (void)
1573 fprintf (stdout,
1574 "Tracing options:\n"
1575 " --trace[=EXPR] Trace every call, optional EXPR controls the scope\n"
1576 "\n"
1577 "EXPR is composed of:\n"
1578 " all All assemblies\n"
1579 " none No assemblies\n"
1580 " program Entry point assembly\n"
1581 " assembly Specifies an assembly\n"
1582 " wrapper All wrappers bridging native and managed code\n"
1583 " M:Type:Method Specifies a method\n"
1584 " N:Namespace Specifies a namespace\n"
1585 " T:Type Specifies a type\n"
1586 " E:Type Specifies stack traces for an exception type\n"
1587 " EXPR Includes expression\n"
1588 " -EXPR Excludes expression\n"
1589 " EXPR,EXPR Multiple expressions\n"
1590 " disabled Don't print any output until toggled via SIGUSR2\n");
1593 static void
1594 mini_debug_usage (void)
1596 fprintf (stdout,
1597 "Debugging options:\n"
1598 " --debug[=OPTIONS] Enable debugging support, optional OPTIONS is a comma\n"
1599 " separated list of options\n"
1600 "\n"
1601 "OPTIONS is composed of:\n"
1602 " casts Enable more detailed InvalidCastException messages.\n"
1603 " mdb-optimizations Disable some JIT optimizations which are normally\n"
1604 " disabled when running inside the debugger.\n"
1605 " This is useful if you plan to attach to the running\n"
1606 " process with the debugger.\n");
1609 #if defined(MONO_ARCH_ARCHITECTURE)
1610 /* Redefine MONO_ARCHITECTURE to include more information */
1611 #undef MONO_ARCHITECTURE
1612 #define MONO_ARCHITECTURE MONO_ARCH_ARCHITECTURE
1613 #endif
1615 static char *
1616 mono_get_version_info (void)
1618 GString *output;
1619 output = g_string_new ("");
1621 #ifdef MONO_KEYWORD_THREAD
1622 g_string_append_printf (output, "\tTLS: __thread\n");
1623 #else
1624 g_string_append_printf (output, "\tTLS: \n");
1625 #endif /* MONO_KEYWORD_THREAD */
1627 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
1628 g_string_append_printf (output, "\tSIGSEGV: altstack\n");
1629 #else
1630 g_string_append_printf (output, "\tSIGSEGV: normal\n");
1631 #endif
1633 #ifdef HAVE_EPOLL
1634 g_string_append_printf (output, "\tNotifications: epoll\n");
1635 #elif defined(HAVE_KQUEUE)
1636 g_string_append_printf (output, "\tNotification: kqueue\n");
1637 #else
1638 g_string_append_printf (output, "\tNotification: Thread + polling\n");
1639 #endif
1641 g_string_append_printf (output, "\tArchitecture: %s\n", MONO_ARCHITECTURE);
1642 g_string_append_printf (output, "\tDisabled: %s\n", DISABLED_FEATURES);
1644 g_string_append_printf (output, "\tMisc: ");
1645 #ifdef MONO_SMALL_CONFIG
1646 g_string_append_printf (output, "smallconfig ");
1647 #endif
1649 #ifdef MONO_BIG_ARRAYS
1650 g_string_append_printf (output, "bigarrays ");
1651 #endif
1653 #if !defined(DISABLE_SDB)
1654 g_string_append_printf (output, "softdebug ");
1655 #endif
1656 g_string_append_printf (output, "\n");
1658 #ifndef DISABLE_INTERPRETER
1659 g_string_append_printf (output, "\tInterpreter: yes\n");
1660 #else
1661 g_string_append_printf (output, "\tInterpreter: no\n");
1662 #endif
1664 #ifdef MONO_ARCH_LLVM_SUPPORTED
1665 #ifdef ENABLE_LLVM
1666 g_string_append_printf (output, "\tLLVM: yes(%d)\n", LLVM_API_VERSION);
1667 #else
1668 g_string_append_printf (output, "\tLLVM: supported, not enabled.\n");
1669 #endif
1670 #endif
1672 g_string_append_printf (output, "\tSuspend: %s\n", mono_threads_suspend_policy_name (mono_threads_suspend_policy ()));
1674 return g_string_free (output, FALSE);
1677 #ifndef MONO_ARCH_AOT_SUPPORTED
1678 #define error_if_aot_unsupported() do {fprintf (stderr, "AOT compilation is not supported on this platform.\n"); exit (1);} while (0)
1679 #else
1680 #define error_if_aot_unsupported()
1681 #endif
1683 static gboolean enable_debugging;
1686 * mono_jit_parse_options:
1688 * Process the command line options in \p argv as done by the runtime executable.
1689 * This should be called before \c mono_jit_init.
1691 void
1692 mono_jit_parse_options (int argc, char * argv[])
1694 int i;
1695 char *trace_options = NULL;
1696 int mini_verbose_level = 0;
1697 guint32 opt;
1700 * Some options have no effect here, since they influence the behavior of
1701 * mono_main ().
1704 opt = mono_parse_default_optimizations (NULL);
1706 /* FIXME: Avoid code duplication */
1707 for (i = 0; i < argc; ++i) {
1708 if (argv [i] [0] != '-')
1709 break;
1710 if (strncmp (argv [i], "--debugger-agent=", 17) == 0) {
1711 MonoDebugOptions *opt = mini_get_debug_options ();
1713 sdb_options = g_strdup (argv [i] + 17);
1714 opt->mdb_optimizations = TRUE;
1715 enable_debugging = TRUE;
1716 } else if (!strcmp (argv [i], "--soft-breakpoints")) {
1717 MonoDebugOptions *opt = mini_get_debug_options ();
1719 opt->soft_breakpoints = TRUE;
1720 opt->explicit_null_checks = TRUE;
1721 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
1722 opt = parse_optimizations (opt, argv [i] + 11, TRUE);
1723 mono_set_optimizations (opt);
1724 } else if (strncmp (argv [i], "-O=", 3) == 0) {
1725 opt = parse_optimizations (opt, argv [i] + 3, TRUE);
1726 mono_set_optimizations (opt);
1727 } else if (strcmp (argv [i], "--trace") == 0) {
1728 trace_options = (char*)"";
1729 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
1730 trace_options = &argv [i][8];
1731 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
1732 mini_verbose_level++;
1733 } else if (strcmp (argv [i], "--breakonex") == 0) {
1734 MonoDebugOptions *opt = mini_get_debug_options ();
1736 opt->break_on_exc = TRUE;
1737 } else if (strcmp (argv [i], "--stats") == 0) {
1738 mono_counters_enable (-1);
1739 mono_atomic_store_bool (&mono_stats.enabled, TRUE);
1740 mono_atomic_store_bool (&mono_jit_stats.enabled, TRUE);
1741 } else if (strcmp (argv [i], "--break") == 0) {
1742 if (i+1 >= argc){
1743 fprintf (stderr, "Missing method name in --break command line option\n");
1744 exit (1);
1747 if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
1748 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
1749 } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
1750 mono_gc_params_set (argv[i] + 12);
1751 } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
1752 mono_gc_debug_set (argv[i] + 11);
1753 } else if (strcmp (argv [i], "--llvm") == 0) {
1754 #ifndef MONO_ARCH_LLVM_SUPPORTED
1755 fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
1756 #elif !defined(ENABLE_LLVM)
1757 fprintf (stderr, "Mono Warning: --llvm not enabled in this runtime.\n");
1758 #else
1759 mono_use_llvm = TRUE;
1760 #endif
1761 } else if (argv [i][0] == '-' && argv [i][1] == '-' && mini_parse_debug_option (argv [i] + 2)) {
1762 } else {
1763 fprintf (stderr, "Unsupported command line option: '%s'\n", argv [i]);
1764 exit (1);
1768 if (trace_options != NULL) {
1770 * Need to call this before mini_init () so we can trace methods
1771 * compiled there too.
1773 mono_jit_trace_calls = mono_trace_set_options (trace_options);
1774 if (mono_jit_trace_calls == NULL)
1775 exit (1);
1778 if (mini_verbose_level)
1779 mono_set_verbose_level (mini_verbose_level);
1782 static void
1783 mono_set_use_smp (int use_smp)
1785 #if HAVE_SCHED_SETAFFINITY
1786 if (!use_smp) {
1787 unsigned long proc_mask = 1;
1788 #ifdef GLIBC_BEFORE_2_3_4_SCHED_SETAFFINITY
1789 sched_setaffinity (getpid(), (gpointer)&proc_mask);
1790 #else
1791 sched_setaffinity (getpid(), sizeof (unsigned long), (const cpu_set_t *)&proc_mask);
1792 #endif
1794 #endif
1797 static void
1798 switch_gc (char* argv[], const char* target_gc)
1800 GString *path;
1802 if (!strcmp (mono_gc_get_gc_name (), target_gc)) {
1803 return;
1806 path = g_string_new (argv [0]);
1808 /*Running mono without any argument*/
1809 if (strstr (argv [0], "-sgen"))
1810 g_string_truncate (path, path->len - 5);
1811 else if (strstr (argv [0], "-boehm"))
1812 g_string_truncate (path, path->len - 6);
1814 g_string_append_c (path, '-');
1815 g_string_append (path, target_gc);
1817 #ifdef HAVE_EXECVP
1818 execvp (path->str, argv);
1819 fprintf (stderr, "Error: Failed to switch to %s gc. mono-%s is not installed.\n", target_gc, target_gc);
1820 #else
1821 fprintf (stderr, "Error: --gc=<NAME> option not supported on this platform.\n");
1822 #endif
1825 #ifdef TARGET_OSX
1828 * tries to increase the minimum number of files, if the number is below 1024
1830 static void
1831 darwin_change_default_file_handles ()
1833 struct rlimit limit;
1835 if (getrlimit (RLIMIT_NOFILE, &limit) == 0){
1836 if (limit.rlim_cur < 1024){
1837 limit.rlim_cur = MAX(1024,limit.rlim_cur);
1838 setrlimit (RLIMIT_NOFILE, &limit);
1843 static void
1844 switch_arch (char* argv[], const char* target_arch)
1846 GString *path;
1847 gsize arch_offset;
1849 if ((strcmp (target_arch, "32") == 0 && strcmp (MONO_ARCHITECTURE, "x86") == 0) ||
1850 (strcmp (target_arch, "64") == 0 && strcmp (MONO_ARCHITECTURE, "amd64") == 0)) {
1851 return; /* matching arch loaded */
1854 path = g_string_new (argv [0]);
1855 arch_offset = path->len -2; /* last two characters */
1857 /* Remove arch suffix if present */
1858 if (strstr (&path->str[arch_offset], "32") || strstr (&path->str[arch_offset], "64")) {
1859 g_string_truncate (path, arch_offset);
1862 g_string_append (path, target_arch);
1864 if (execvp (path->str, argv) < 0) {
1865 fprintf (stderr, "Error: --arch=%s Failed to switch to '%s'.\n", target_arch, path->str);
1866 exit (1);
1870 #endif
1872 #define MONO_HANDLERS_ARGUMENT "--handlers="
1873 #define MONO_HANDLERS_ARGUMENT_LEN G_N_ELEMENTS(MONO_HANDLERS_ARGUMENT)-1
1875 static void
1876 apply_root_domain_configuration_file_bindings (MonoDomain *domain, char *root_domain_configuration_file)
1878 g_assert (domain->setup == NULL || domain->setup->configuration_file == NULL);
1879 g_assert (!domain->assembly_bindings_parsed);
1881 mono_domain_parse_assembly_bindings (domain, 0, 0, root_domain_configuration_file);
1885 static void
1886 mono_enable_interp (const char *opts)
1888 mono_runtime_set_execution_mode (MONO_EE_MODE_INTERP);
1889 if (opts)
1890 mono_interp_opts_string = opts;
1892 #ifdef DISABLE_INTERPRETER
1893 g_error ("Mono IL interpreter support is missing\n");
1894 #endif
1896 #ifdef MONO_CROSS_COMPILE
1897 g_error ("--interpreter on cross-compile runtimes not supported\n");
1898 #endif
1900 #ifndef MONO_ARCH_INTERPRETER_SUPPORTED
1901 g_error ("--interpreter not supported on this architecture.\n");
1902 #endif
1906 static int
1907 mono_exec_regression_internal (int verbose_level, int count, char *images [], gboolean single_method)
1909 mono_do_single_method_regression = single_method;
1910 if (mono_use_interpreter) {
1911 if (mono_interp_regression_list (verbose_level, count, images)) {
1912 g_print ("Regression ERRORS!\n");
1913 return 1;
1915 return 0;
1917 if (mini_regression_list (verbose_level, count, images)) {
1918 g_print ("Regression ERRORS!\n");
1919 return 1;
1921 return 0;
1926 * Returns TRUE for success, FALSE for failure.
1928 gboolean
1929 mono_regression_test_step (int verbose_level, const char *image, const char *method_name)
1931 if (method_name) {
1932 //TODO
1933 } else {
1934 do_regression_retries = TRUE;
1937 char *images[] = {
1938 (char*)image,
1939 NULL
1942 return mono_exec_regression_internal (verbose_level, 1, images, FALSE) == 0;
1945 #ifdef ENABLE_ICALL_SYMBOL_MAP
1946 /* Print the icall table as JSON */
1947 static void
1948 print_icall_table (void)
1950 // We emit some dummy values to make the code simpler
1952 printf ("[\n{ \"klass\": \"\", \"icalls\": [");
1953 #define NOHANDLES(inner) inner
1954 #define HANDLES(id, name, func, ...) printf ("\t,{ \"name\": \"%s\", \"func\": \"%s_raw\", \"handles\": true }\n", name, #func);
1955 #define HANDLES_REUSE_WRAPPER HANDLES
1956 #define MONO_HANDLE_REGISTER_ICALL(...) /* nothing */
1957 #define ICALL_TYPE(id,name,first) printf ("]},\n { \"klass\":\"%s\", \"icalls\": [{} ", name);
1958 #define ICALL(id,name,func) printf ("\t,{ \"name\": \"%s\", \"func\": \"%s\", \"handles\": false }\n", name, #func);
1959 #include <mono/metadata/icall-def.h>
1961 printf ("]}\n]\n");
1963 #endif
1966 * mono_main:
1967 * \param argc number of arguments in the argv array
1968 * \param argv array of strings containing the startup arguments
1969 * Launches the Mono JIT engine and parses all the command line options
1970 * in the same way that the mono command line VM would.
1973 mono_main (int argc, char* argv[])
1975 MainThreadArgs main_args;
1976 MonoAssembly *assembly;
1977 MonoMethodDesc *desc;
1978 MonoMethod *method;
1979 MonoCompile *cfg;
1980 MonoDomain *domain;
1981 MonoImageOpenStatus open_status;
1982 const char* aname, *mname = NULL;
1983 char *config_file = NULL;
1984 int i, count = 1;
1985 guint32 opt, action = DO_EXEC, recompilation_times = 1;
1986 MonoGraphOptions mono_graph_options = (MonoGraphOptions)0;
1987 int mini_verbose_level = 0;
1988 char *trace_options = NULL;
1989 char *aot_options = NULL;
1990 char *forced_version = NULL;
1991 GPtrArray *agents = NULL;
1992 char *attach_options = NULL;
1993 char *extra_bindings_config_file = NULL;
1994 #ifdef MONO_JIT_INFO_TABLE_TEST
1995 int test_jit_info_table = FALSE;
1996 #endif
1997 #ifdef HOST_WIN32
1998 int mixed_mode = FALSE;
1999 #endif
2001 #ifdef MOONLIGHT
2002 #ifndef HOST_WIN32
2003 /* stdout defaults to block buffering if it's not writing to a terminal, which
2004 * happens with our test harness: we redirect stdout to capture it. Force line
2005 * buffering in all cases. */
2006 setlinebuf (stdout);
2007 #endif
2008 #endif
2010 setlocale (LC_ALL, "");
2012 #if TARGET_OSX
2013 darwin_change_default_file_handles ();
2014 #endif
2016 if (g_hasenv ("MONO_NO_SMP"))
2017 mono_set_use_smp (FALSE);
2019 #ifdef MONO_JEMALLOC_ENABLED
2021 gboolean use_jemalloc = FALSE;
2022 #ifdef MONO_JEMALLOC_DEFAULT
2023 use_jemalloc = TRUE;
2024 #endif
2025 if (!use_jemalloc)
2026 use_jemalloc = g_hasenv ("MONO_USE_JEMALLOC");
2028 if (use_jemalloc)
2029 mono_init_jemalloc ();
2031 #endif
2033 g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
2034 g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
2036 opt = mono_parse_default_optimizations (NULL);
2038 for (i = 1; i < argc; ++i) {
2039 if (argv [i] [0] != '-')
2040 break;
2041 if (strcmp (argv [i], "--regression") == 0) {
2042 action = DO_REGRESSION;
2043 } else if (strncmp (argv [i], "--single-method=", 16) == 0) {
2044 char *full_opts = g_strdup_printf ("-all,%s", argv [i] + 16);
2045 action = DO_SINGLE_METHOD_REGRESSION;
2046 mono_single_method_regression_opt = parse_optimizations (opt, full_opts, TRUE);
2047 g_free (full_opts);
2048 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
2049 mini_verbose_level++;
2050 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
2051 char *build = mono_get_runtime_build_info ();
2052 char *gc_descr;
2054 g_print ("Mono JIT compiler version %s\nCopyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com\n", build);
2055 g_free (build);
2056 char *info = mono_get_version_info ();
2057 g_print (info);
2058 g_free (info);
2060 gc_descr = mono_gc_get_description ();
2061 g_print ("\tGC: %s\n", gc_descr);
2062 g_free (gc_descr);
2063 return 0;
2064 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
2065 mini_usage ();
2066 return 0;
2067 } else if (strcmp (argv [i], "--help-trace") == 0){
2068 mini_trace_usage ();
2069 return 0;
2070 } else if (strcmp (argv [i], "--help-devel") == 0){
2071 mini_usage_jitdeveloper ();
2072 return 0;
2073 } else if (strcmp (argv [i], "--help-debug") == 0){
2074 mini_debug_usage ();
2075 return 0;
2076 } else if (strcmp (argv [i], "--list-opt") == 0){
2077 mini_usage_list_opt ();
2078 return 0;
2079 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
2080 if (i + 1 >= argc){
2081 fprintf (stderr, "error: --statfile requires a filename argument\n");
2082 return 1;
2084 mini_stats_fd = fopen (argv [++i], "w+");
2085 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
2086 opt = parse_optimizations (opt, argv [i] + 11, TRUE);
2087 } else if (strncmp (argv [i], "-O=", 3) == 0) {
2088 opt = parse_optimizations (opt, argv [i] + 3, TRUE);
2089 } else if (strncmp (argv [i], "--bisect=", 9) == 0) {
2090 char *param = argv [i] + 9;
2091 char *sep = strchr (param, ':');
2092 if (!sep) {
2093 fprintf (stderr, "Error: --bisect requires OPT:FILENAME\n");
2094 return 1;
2096 char *opt_string = g_strndup (param, sep - param);
2097 guint32 opt = parse_optimizations (0, opt_string, FALSE);
2098 g_free (opt_string);
2099 mono_set_bisect_methods (opt, sep + 1);
2100 } else if (strcmp (argv [i], "--gc=sgen") == 0) {
2101 switch_gc (argv, "sgen");
2102 } else if (strcmp (argv [i], "--gc=boehm") == 0) {
2103 switch_gc (argv, "boehm");
2104 } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
2105 mono_gc_params_set (argv[i] + 12);
2106 } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
2107 mono_gc_debug_set (argv[i] + 11);
2109 #ifdef TARGET_OSX
2110 else if (strcmp (argv [i], "--arch=32") == 0) {
2111 switch_arch (argv, "32");
2112 } else if (strcmp (argv [i], "--arch=64") == 0) {
2113 switch_arch (argv, "64");
2115 #endif
2116 else if (strcmp (argv [i], "--config") == 0) {
2117 if (i +1 >= argc){
2118 fprintf (stderr, "error: --config requires a filename argument\n");
2119 return 1;
2121 config_file = argv [++i];
2122 #ifdef HOST_WIN32
2123 } else if (strcmp (argv [i], "--mixed-mode") == 0) {
2124 mixed_mode = TRUE;
2125 #endif
2126 } else if (strcmp (argv [i], "--ncompile") == 0) {
2127 if (i + 1 >= argc){
2128 fprintf (stderr, "error: --ncompile requires an argument\n");
2129 return 1;
2131 count = atoi (argv [++i]);
2132 action = DO_BENCH;
2133 } else if (strcmp (argv [i], "--trace") == 0) {
2134 trace_options = (char*)"";
2135 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
2136 trace_options = &argv [i][8];
2137 } else if (strcmp (argv [i], "--breakonex") == 0) {
2138 MonoDebugOptions *opt = mini_get_debug_options ();
2140 opt->break_on_exc = TRUE;
2141 } else if (strcmp (argv [i], "--break") == 0) {
2142 if (i+1 >= argc){
2143 fprintf (stderr, "Missing method name in --break command line option\n");
2144 return 1;
2147 if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
2148 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
2149 } else if (strcmp (argv [i], "--break-at-bb") == 0) {
2150 if (i + 2 >= argc) {
2151 fprintf (stderr, "Missing method name or bb num in --break-at-bb command line option.");
2152 return 1;
2154 mono_break_at_bb_method = mono_method_desc_new (argv [++i], TRUE);
2155 if (mono_break_at_bb_method == NULL) {
2156 fprintf (stderr, "Method name is in a bad format in --break-at-bb command line option.");
2157 return 1;
2159 mono_break_at_bb_bb_num = atoi (argv [++i]);
2160 } else if (strcmp (argv [i], "--inject-async-exc") == 0) {
2161 if (i + 2 >= argc) {
2162 fprintf (stderr, "Missing method name or position in --inject-async-exc command line option\n");
2163 return 1;
2165 mono_inject_async_exc_method = mono_method_desc_new (argv [++i], TRUE);
2166 if (mono_inject_async_exc_method == NULL) {
2167 fprintf (stderr, "Method name is in a bad format in --inject-async-exc command line option\n");
2168 return 1;
2170 mono_inject_async_exc_pos = atoi (argv [++i]);
2171 } else if (strcmp (argv [i], "--verify-all") == 0) {
2172 mono_verifier_enable_verify_all ();
2173 } else if (strcmp (argv [i], "--full-aot") == 0) {
2174 mono_jit_set_aot_mode (MONO_AOT_MODE_FULL);
2175 } else if (strcmp (argv [i], "--llvmonly") == 0) {
2176 mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY);
2177 } else if (strcmp (argv [i], "--hybrid-aot") == 0) {
2178 mono_jit_set_aot_mode (MONO_AOT_MODE_HYBRID);
2179 } else if (strcmp (argv [i], "--full-aot-interp") == 0) {
2180 mono_jit_set_aot_mode (MONO_AOT_MODE_INTERP);
2181 } else if (strcmp (argv [i], "--llvmonly-interp") == 0) {
2182 mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY_INTERP);
2183 } else if (strcmp (argv [i], "--print-vtable") == 0) {
2184 mono_print_vtable = TRUE;
2185 } else if (strcmp (argv [i], "--stats") == 0) {
2186 mono_counters_enable (-1);
2187 mono_atomic_store_bool (&mono_stats.enabled, TRUE);
2188 mono_atomic_store_bool (&mono_jit_stats.enabled, TRUE);
2189 #ifndef DISABLE_AOT
2190 } else if (strcmp (argv [i], "--aot") == 0) {
2191 error_if_aot_unsupported ();
2192 mono_compile_aot = TRUE;
2193 } else if (strncmp (argv [i], "--aot=", 6) == 0) {
2194 error_if_aot_unsupported ();
2195 mono_compile_aot = TRUE;
2196 if (aot_options) {
2197 char *tmp = g_strdup_printf ("%s,%s", aot_options, &argv [i][6]);
2198 g_free (aot_options);
2199 aot_options = tmp;
2200 } else {
2201 aot_options = g_strdup (&argv [i][6]);
2203 #endif
2204 } else if (strncmp (argv [i], "--apply-bindings=", 17) == 0) {
2205 extra_bindings_config_file = &argv[i][17];
2206 } else if (strncmp (argv [i], "--aot-path=", 11) == 0) {
2207 char **splitted;
2209 splitted = g_strsplit (argv [i] + 11, G_SEARCHPATH_SEPARATOR_S, 1000);
2210 while (*splitted) {
2211 char *tmp = *splitted;
2212 mono_aot_paths = g_list_append (mono_aot_paths, g_strdup (tmp));
2213 g_free (tmp);
2214 splitted++;
2216 } else if (strncmp (argv [i], "--compile-all=", 14) == 0) {
2217 action = DO_COMPILE;
2218 recompilation_times = atoi (argv [i] + 14);
2219 } else if (strcmp (argv [i], "--compile-all") == 0) {
2220 action = DO_COMPILE;
2221 } else if (strncmp (argv [i], "--runtime=", 10) == 0) {
2222 forced_version = &argv [i][10];
2223 } else if (strcmp (argv [i], "--jitmap") == 0) {
2224 mono_enable_jit_map ();
2225 } else if (strcmp (argv [i], "--profile") == 0) {
2226 mini_add_profiler_argument (NULL);
2227 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
2228 mini_add_profiler_argument (argv [i] + 10);
2229 } else if (strncmp (argv [i], "--agent=", 8) == 0) {
2230 if (agents == NULL)
2231 agents = g_ptr_array_new ();
2232 g_ptr_array_add (agents, argv [i] + 8);
2233 } else if (strncmp (argv [i], "--attach=", 9) == 0) {
2234 attach_options = argv [i] + 9;
2235 } else if (strcmp (argv [i], "--compile") == 0) {
2236 if (i + 1 >= argc){
2237 fprintf (stderr, "error: --compile option requires a method name argument\n");
2238 return 1;
2241 mname = argv [++i];
2242 action = DO_BENCH;
2243 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
2244 if (i + 1 >= argc){
2245 fprintf (stderr, "error: --graph option requires a method name argument\n");
2246 return 1;
2249 mono_graph_options = mono_parse_graph_options (argv [i] + 8);
2250 mname = argv [++i];
2251 action = DO_DRAW;
2252 } else if (strcmp (argv [i], "--graph") == 0) {
2253 if (i + 1 >= argc){
2254 fprintf (stderr, "error: --graph option requires a method name argument\n");
2255 return 1;
2258 mname = argv [++i];
2259 mono_graph_options = MONO_GRAPH_CFG;
2260 action = DO_DRAW;
2261 } else if (strcmp (argv [i], "--debug") == 0) {
2262 enable_debugging = TRUE;
2263 } else if (strncmp (argv [i], "--debug=", 8) == 0) {
2264 enable_debugging = TRUE;
2265 if (!parse_debug_options (argv [i] + 8))
2266 return 1;
2267 } else if (strncmp (argv [i], "--debugger-agent=", 17) == 0) {
2268 MonoDebugOptions *opt = mini_get_debug_options ();
2270 sdb_options = g_strdup (argv [i] + 17);
2271 opt->mdb_optimizations = TRUE;
2272 enable_debugging = TRUE;
2273 } else if (strcmp (argv [i], "--security") == 0) {
2274 #ifndef DISABLE_SECURITY
2275 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2276 #else
2277 fprintf (stderr, "error: --security: not compiled with security manager support");
2278 return 1;
2279 #endif
2280 } else if (strncmp (argv [i], "--security=", 11) == 0) {
2281 /* Note: validil, and verifiable need to be
2282 accepted even if DISABLE_SECURITY is defined. */
2284 if (strcmp (argv [i] + 11, "core-clr") == 0) {
2285 #ifndef DISABLE_SECURITY
2286 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2287 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
2288 #else
2289 fprintf (stderr, "error: --security: not compiled with CoreCLR support");
2290 return 1;
2291 #endif
2292 } else if (strcmp (argv [i] + 11, "core-clr-test") == 0) {
2293 #ifndef DISABLE_SECURITY
2294 /* fixme should we enable verifiable code here?*/
2295 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
2296 mono_security_core_clr_test = TRUE;
2297 #else
2298 fprintf (stderr, "error: --security: not compiled with CoreCLR support");
2299 return 1;
2300 #endif
2301 } else if (strcmp (argv [i] + 11, "cas") == 0) {
2302 #ifndef DISABLE_SECURITY
2303 fprintf (stderr, "warning: --security=cas not supported.");
2304 #else
2305 fprintf (stderr, "error: --security: not compiled with CAS support");
2306 return 1;
2307 #endif
2308 } else if (strcmp (argv [i] + 11, "validil") == 0) {
2309 mono_verifier_set_mode (MONO_VERIFIER_MODE_VALID);
2310 } else if (strcmp (argv [i] + 11, "verifiable") == 0) {
2311 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2312 } else {
2313 fprintf (stderr, "error: --security= option has invalid argument (cas, core-clr, verifiable or validil)\n");
2314 return 1;
2316 } else if (strcmp (argv [i], "--desktop") == 0) {
2317 mono_gc_set_desktop_mode ();
2318 /* Put more desktop-specific optimizations here */
2319 } else if (strcmp (argv [i], "--server") == 0){
2320 mono_config_set_server_mode (TRUE);
2321 /* Put more server-specific optimizations here */
2322 } else if (strcmp (argv [i], "--inside-mdb") == 0) {
2323 action = DO_DEBUGGER;
2324 } else if (strncmp (argv [i], "--wapi=", 7) == 0) {
2325 fprintf (stderr, "--wapi= option no longer supported\n.");
2326 return 1;
2327 } else if (strcmp (argv [i], "--no-x86-stack-align") == 0) {
2328 mono_do_x86_stack_align = FALSE;
2329 #ifdef MONO_JIT_INFO_TABLE_TEST
2330 } else if (strcmp (argv [i], "--test-jit-info-table") == 0) {
2331 test_jit_info_table = TRUE;
2332 #endif
2333 } else if (strcmp (argv [i], "--llvm") == 0) {
2334 #ifndef MONO_ARCH_LLVM_SUPPORTED
2335 fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
2336 #elif !defined(ENABLE_LLVM)
2337 fprintf (stderr, "Mono Warning: --llvm not enabled in this runtime.\n");
2338 #else
2339 mono_use_llvm = TRUE;
2340 #endif
2341 } else if (strcmp (argv [i], "--nollvm") == 0){
2342 mono_use_llvm = FALSE;
2343 } else if ((strcmp (argv [i], "--interpreter") == 0) || !strcmp (argv [i], "--interp")) {
2344 mono_enable_interp (NULL);
2345 } else if (strncmp (argv [i], "--interp=", 9) == 0) {
2346 mono_enable_interp (argv [i] + 9);
2347 } else if (strcmp (argv [i], "--print-icall-table") == 0) {
2348 #ifdef ENABLE_ICALL_SYMBOL_MAP
2349 print_icall_table ();
2350 exit (0);
2351 #else
2352 fprintf (stderr, "--print-icall-table requires a runtime configured with the --enable-icall-symbol-map option.\n");
2353 exit (1);
2354 #endif
2355 } else if (strncmp (argv [i], "--assembly-loader=", strlen("--assembly-loader=")) == 0) {
2356 gchar *arg = argv [i] + strlen ("--assembly-loader=");
2357 if (strcmp (arg, "strict") == 0)
2358 mono_loader_set_strict_strong_names (TRUE);
2359 else if (strcmp (arg, "legacy") == 0)
2360 mono_loader_set_strict_strong_names (FALSE);
2361 else
2362 fprintf (stderr, "Warning: unknown argument to --assembly-loader. Should be \"strict\" or \"legacy\"\n");
2363 } else if (strncmp (argv [i], MONO_HANDLERS_ARGUMENT, MONO_HANDLERS_ARGUMENT_LEN) == 0) {
2364 //Install specific custom handlers.
2365 if (!mono_runtime_install_custom_handlers (argv[i] + MONO_HANDLERS_ARGUMENT_LEN)) {
2366 fprintf (stderr, "error: " MONO_HANDLERS_ARGUMENT ", one or more unknown handlers: '%s'\n", argv [i]);
2367 return 1;
2369 } else if (strcmp (argv [i], "--help-handlers") == 0) {
2370 mono_runtime_install_custom_handlers_usage ();
2371 return 0;
2372 } else if (strncmp (argv [i], "--response=", 11) == 0){
2373 gchar *response_content;
2374 gchar *response_options;
2375 gsize response_content_len;
2377 if (!g_file_get_contents (&argv[i][11], &response_content, &response_content_len, NULL)){
2378 fprintf (stderr, "The specified response file can not be read\n");
2379 exit (1);
2382 response_options = response_content;
2384 // Check for UTF8 BOM in file and remove if found.
2385 if (response_content_len >= 3 && response_content [0] == '\xef' && response_content [1] == '\xbb' && response_content [2] == '\xbf') {
2386 response_content_len -= 3;
2387 response_options += 3;
2390 if (response_content_len == 0) {
2391 fprintf (stderr, "The specified response file is empty\n");
2392 exit (1);
2395 mono_parse_response_options (response_options, &argc, &argv, FALSE);
2396 g_free (response_content);
2397 } else if (argv [i][0] == '-' && argv [i][1] == '-' && mini_parse_debug_option (argv [i] + 2)) {
2398 } else {
2399 fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
2400 return 1;
2404 #if defined(DISABLE_HW_TRAPS) || defined(MONO_ARCH_DISABLE_HW_TRAPS)
2405 // Signal handlers not available
2407 MonoDebugOptions *opt = mini_get_debug_options ();
2408 opt->explicit_null_checks = TRUE;
2410 #endif
2412 if (!argv [i]) {
2413 mini_usage ();
2414 return 1;
2418 * XXX: verify if other OSes need it; many platforms seem to have it so that
2419 * mono_w32process_get_path -> mono_w32process_get_name, and the name is not
2420 * necessarily a path instead of just the program name
2422 #if defined (_AIX)
2424 * mono_w32process_get_path on these can only return a name, not a path;
2425 * which may not be good for us if the mono command name isn't on $PATH,
2426 * like in CI scenarios. chances are argv based is fine if we inherited
2427 * the environment variables.
2429 mono_w32process_set_cli_launcher (argv [0]);
2430 #elif !defined(HOST_WIN32) && defined(HAVE_UNISTD_H)
2432 * If we are not embedded, use the mono runtime executable to run managed exe's.
2435 char *runtime_path;
2437 runtime_path = mono_w32process_get_path (getpid ());
2438 if (runtime_path) {
2439 mono_w32process_set_cli_launcher (runtime_path);
2440 g_free (runtime_path);
2443 #endif
2445 if (g_hasenv ("MONO_XDEBUG"))
2446 enable_debugging = TRUE;
2448 #ifdef MONO_CROSS_COMPILE
2449 if (!mono_compile_aot) {
2450 fprintf (stderr, "This mono runtime is compiled for cross-compiling. Only the --aot option is supported.\n");
2451 exit (1);
2453 #if TARGET_SIZEOF_VOID_P == 4 && (defined(TARGET_ARM64) || defined(TARGET_AMD64)) && !defined(MONO_ARCH_ILP32)
2454 fprintf (stderr, "Can't cross-compile on 32-bit platforms to 64-bit architecture.\n");
2455 exit (1);
2456 #endif
2457 #endif
2459 if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
2460 g_set_prgname (argv[i]);
2463 mono_counters_init ();
2465 #ifndef HOST_WIN32
2466 mono_w32handle_init ();
2467 #endif
2469 /* Set rootdir before loading config */
2470 mono_set_rootdir ();
2472 mono_attach_parse_options (attach_options);
2474 if (trace_options != NULL){
2476 * Need to call this before mini_init () so we can trace methods
2477 * compiled there too.
2479 mono_jit_trace_calls = mono_trace_set_options (trace_options);
2480 if (mono_jit_trace_calls == NULL)
2481 exit (1);
2484 #ifdef DISABLE_JIT
2485 if (!mono_aot_only && !mono_use_interpreter) {
2486 fprintf (stderr, "This runtime has been configured with --enable-minimal=jit, so the --full-aot command line option is required.\n");
2487 exit (1);
2489 #endif
2491 if (action == DO_DEBUGGER) {
2492 enable_debugging = TRUE;
2493 g_print ("The Mono Debugger is no longer supported.\n");
2494 return 1;
2495 } else if (enable_debugging)
2496 mono_debug_init (MONO_DEBUG_FORMAT_MONO);
2498 #ifdef HOST_WIN32
2499 if (mixed_mode)
2500 mono_load_coree (argv [i]);
2501 #endif
2503 /* Parse gac loading options before loading assemblies. */
2504 if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER || action == DO_REGRESSION) {
2505 mono_config_parse (config_file);
2508 mono_set_defaults (mini_verbose_level, opt);
2509 domain = mini_init (argv [i], forced_version);
2511 mono_gc_set_stack_end (&domain);
2513 if (agents) {
2514 int i;
2516 for (i = 0; i < agents->len; ++i) {
2517 int res = load_agent (domain, (char*)g_ptr_array_index (agents, i));
2518 if (res) {
2519 g_ptr_array_free (agents, TRUE);
2520 mini_cleanup (domain);
2521 return 1;
2525 g_ptr_array_free (agents, TRUE);
2528 switch (action) {
2529 case DO_SINGLE_METHOD_REGRESSION:
2530 case DO_REGRESSION:
2531 return mono_exec_regression_internal (mini_verbose_level, argc -i, argv + i, action == DO_SINGLE_METHOD_REGRESSION);
2533 case DO_BENCH:
2534 if (argc - i != 1 || mname == NULL) {
2535 g_print ("Usage: mini --ncompile num --compile method assembly\n");
2536 mini_cleanup (domain);
2537 return 1;
2539 aname = argv [i];
2540 break;
2541 case DO_COMPILE:
2542 if (argc - i != 1) {
2543 mini_usage ();
2544 mini_cleanup (domain);
2545 return 1;
2547 aname = argv [i];
2548 break;
2549 case DO_DRAW:
2550 if (argc - i != 1 || mname == NULL) {
2551 mini_usage ();
2552 mini_cleanup (domain);
2553 return 1;
2555 aname = argv [i];
2556 break;
2557 default:
2558 if (argc - i < 1) {
2559 mini_usage ();
2560 mini_cleanup (domain);
2561 return 1;
2563 aname = argv [i];
2564 break;
2567 #ifdef MONO_JIT_INFO_TABLE_TEST
2568 if (test_jit_info_table)
2569 jit_info_table_test (domain);
2570 #endif
2572 if (mono_compile_aot && extra_bindings_config_file != NULL) {
2573 apply_root_domain_configuration_file_bindings (domain, extra_bindings_config_file);
2576 MonoAssemblyOpenRequest open_req;
2577 mono_assembly_request_prepare (&open_req.request, sizeof (open_req), MONO_ASMCTX_DEFAULT);
2578 assembly = mono_assembly_request_open (aname, &open_req, &open_status);
2579 if (!assembly) {
2580 fprintf (stderr, "Cannot open assembly '%s': %s.\n", aname, mono_image_strerror (open_status));
2581 mini_cleanup (domain);
2582 return 2;
2585 mono_callspec_set_assembly (assembly);
2587 if (mono_compile_aot || action == DO_EXEC) {
2588 const char *error;
2590 //mono_set_rootdir ();
2592 error = mono_check_corlib_version ();
2593 if (error) {
2594 fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
2595 fprintf (stderr, "Loaded from: %s\n",
2596 mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown");
2597 fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.mono-project.com/download.\n");
2598 exit (1);
2601 #if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
2602 /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
2603 if (!enable_debugging && !mono_compile_aot && mono_assembly_get_image_internal (assembly)->image_info->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
2604 FreeConsole ();
2605 #endif
2607 main_args.domain = domain;
2608 main_args.file = aname;
2609 main_args.argc = argc - i;
2610 main_args.argv = argv + i;
2611 main_args.opts = opt;
2612 main_args.aot_options = aot_options;
2613 main_thread_handler (&main_args);
2614 mono_thread_manage ();
2616 mini_cleanup (domain);
2618 /* Look up return value from System.Environment.ExitCode */
2619 i = mono_environment_exitcode_get ();
2620 return i;
2621 } else if (action == DO_COMPILE) {
2622 compile_all_methods (assembly, mini_verbose_level, opt, recompilation_times);
2623 mini_cleanup (domain);
2624 return 0;
2625 } else if (action == DO_DEBUGGER) {
2626 return 1;
2628 desc = mono_method_desc_new (mname, 0);
2629 if (!desc) {
2630 g_print ("Invalid method name %s\n", mname);
2631 mini_cleanup (domain);
2632 return 3;
2634 method = mono_method_desc_search_in_image (desc, mono_assembly_get_image_internal (assembly));
2635 if (!method) {
2636 g_print ("Cannot find method %s\n", mname);
2637 mini_cleanup (domain);
2638 return 3;
2641 #ifndef DISABLE_JIT
2642 if (action == DO_DRAW) {
2643 int part = 0;
2645 switch (mono_graph_options) {
2646 case MONO_GRAPH_DTREE:
2647 part = 1;
2648 opt |= MONO_OPT_LOOP;
2649 break;
2650 case MONO_GRAPH_CFG_CODE:
2651 part = 1;
2652 break;
2653 case MONO_GRAPH_CFG_SSA:
2654 part = 2;
2655 break;
2656 case MONO_GRAPH_CFG_OPTCODE:
2657 part = 3;
2658 break;
2659 default:
2660 break;
2663 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2664 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
2665 MonoMethod *nm;
2666 nm = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
2667 cfg = mini_method_compile (nm, opt, mono_get_root_domain (), (JitFlags)0, part, -1);
2669 else
2670 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, part, -1);
2671 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
2672 g_warning ("no SSA info available (use -O=deadce)");
2673 return 1;
2675 mono_draw_graph (cfg, mono_graph_options);
2676 mono_destroy_compile (cfg);
2678 } else if (action == DO_BENCH) {
2679 if (mini_stats_fd) {
2680 const char *n;
2681 double no_opt_time = 0.0;
2682 GTimer *timer = g_timer_new ();
2683 fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n",
2684 mono_method_full_name (method, TRUE));
2685 fprintf (mini_stats_fd, "@data = (\n");
2686 fprintf (mini_stats_fd, "[");
2687 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
2688 opt = opt_sets [i];
2689 n = mono_opt_descr (opt);
2690 if (!n [0])
2691 n = "none";
2692 fprintf (mini_stats_fd, "\"%s\",", n);
2694 fprintf (mini_stats_fd, "],\n[");
2696 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
2697 int j;
2698 double elapsed;
2699 opt = opt_sets [i];
2700 g_timer_start (timer);
2701 for (j = 0; j < count; ++j) {
2702 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2703 mono_destroy_compile (cfg);
2705 g_timer_stop (timer);
2706 elapsed = g_timer_elapsed (timer, NULL);
2707 if (!opt)
2708 no_opt_time = elapsed;
2709 fprintf (mini_stats_fd, "%f, ", elapsed);
2711 fprintf (mini_stats_fd, "]");
2712 if (no_opt_time > 0.0) {
2713 fprintf (mini_stats_fd, ", \n[");
2714 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++)
2715 fprintf (mini_stats_fd, "%f,", no_opt_time);
2716 fprintf (mini_stats_fd, "]");
2718 fprintf (mini_stats_fd, ");\n");
2719 } else {
2720 for (i = 0; i < count; ++i) {
2721 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2722 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
2723 method = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
2725 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2726 mono_destroy_compile (cfg);
2729 } else {
2730 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2731 mono_destroy_compile (cfg);
2733 #endif
2735 mini_cleanup (domain);
2736 return 0;
2740 * mono_jit_init:
2742 MonoDomain *
2743 mono_jit_init (const char *file)
2745 return mini_init (file, NULL);
2749 * mono_jit_init_version:
2750 * \param domain_name the name of the root domain
2751 * \param runtime_version the version of the runtime to load
2753 * Use this version when you want to force a particular runtime
2754 * version to be used. By default Mono will pick the runtime that is
2755 * referenced by the initial assembly (specified in \p file), this
2756 * routine allows programmers to specify the actual runtime to be used
2757 * as the initial runtime is inherited by all future assemblies loaded
2758 * (since Mono does not support having more than one mscorlib runtime
2759 * loaded at once).
2761 * The \p runtime_version can be one of these strings: "v4.0.30319" for
2762 * desktop, "mobile" for mobile or "moonlight" for Silverlight compat.
2763 * If an unrecognized string is input, the vm will default to desktop.
2765 * \returns the \c MonoDomain representing the domain where the assembly
2766 * was loaded.
2768 MonoDomain *
2769 mono_jit_init_version (const char *domain_name, const char *runtime_version)
2771 return mini_init (domain_name, runtime_version);
2775 * mono_jit_cleanup:
2777 void
2778 mono_jit_cleanup (MonoDomain *domain)
2780 MONO_ENTER_GC_UNSAFE;
2781 mono_thread_manage ();
2783 mini_cleanup (domain);
2784 MONO_EXIT_GC_UNSAFE;
2787 void
2788 mono_jit_set_aot_only (gboolean val)
2790 mono_aot_only = val;
2791 mono_ee_features.use_aot_trampolines = val;
2794 static void
2795 mono_runtime_set_execution_mode (MonoEEMode mode)
2797 memset (&mono_ee_features, 0, sizeof (mono_ee_features));
2799 switch (mode) {
2800 case MONO_AOT_MODE_LLVMONLY:
2801 mono_aot_only = TRUE;
2802 mono_llvm_only = TRUE;
2804 mono_ee_features.use_aot_trampolines = TRUE;
2805 break;
2807 case MONO_AOT_MODE_FULL:
2808 mono_aot_only = TRUE;
2810 mono_ee_features.use_aot_trampolines = TRUE;
2811 break;
2813 case MONO_AOT_MODE_HYBRID:
2814 mono_set_generic_sharing_vt_supported (TRUE);
2815 mono_set_partial_sharing_supported (TRUE);
2816 break;
2818 case MONO_AOT_MODE_INTERP:
2819 mono_aot_only = TRUE;
2820 mono_use_interpreter = TRUE;
2822 mono_ee_features.use_aot_trampolines = TRUE;
2823 break;
2825 case MONO_AOT_MODE_INTERP_LLVMONLY:
2826 mono_aot_only = TRUE;
2827 mono_use_interpreter = TRUE;
2828 mono_llvm_only = TRUE;
2830 mono_ee_features.force_use_interpreter = TRUE;
2831 break;
2833 case MONO_AOT_MODE_LLVMONLY_INTERP:
2834 mono_aot_only = TRUE;
2835 mono_use_interpreter = TRUE;
2836 mono_llvm_only = TRUE;
2837 break;
2839 case MONO_EE_MODE_INTERP:
2840 mono_use_interpreter = TRUE;
2842 mono_ee_features.force_use_interpreter = TRUE;
2843 break;
2845 case MONO_AOT_MODE_NORMAL:
2846 case MONO_AOT_MODE_NONE:
2847 break;
2849 default:
2850 g_error ("Unknown execution-mode %d", mode);
2855 * mono_jit_set_aot_mode:
2857 void
2858 mono_jit_set_aot_mode (MonoAotMode mode)
2860 /* we don't want to set mono_aot_mode twice */
2861 static gboolean inited;
2863 g_assert (!inited);
2864 mono_aot_mode = mode;
2865 inited = TRUE;
2867 mono_runtime_set_execution_mode ((MonoEEMode)mode);
2870 mono_bool
2871 mono_jit_aot_compiling (void)
2873 return mono_compile_aot;
2877 * mono_jit_set_trace_options:
2878 * \param options string representing the trace options
2879 * Set the options of the tracing engine. This function can be called before initializing
2880 * the mono runtime. See the --trace mono(1) manpage for the options format.
2882 * \returns TRUE if the options were parsed and set correctly, FALSE otherwise.
2884 gboolean
2885 mono_jit_set_trace_options (const char* options)
2887 MonoCallSpec *trace_opt = mono_trace_set_options (options);
2888 if (trace_opt == NULL)
2889 return FALSE;
2890 mono_jit_trace_calls = trace_opt;
2891 return TRUE;
2895 * mono_set_signal_chaining:
2897 * Enable/disable signal chaining. This should be called before \c mono_jit_init.
2898 * If signal chaining is enabled, the runtime saves the original signal handlers before
2899 * installing its own handlers, and calls the original ones in the following cases:
2900 * - a \c SIGSEGV / \c SIGABRT signal received while executing native (i.e. not JITted) code.
2901 * - \c SIGPROF
2902 * - \c SIGFPE
2903 * - \c SIGQUIT
2904 * - \c SIGUSR2
2905 * Signal chaining only works on POSIX platforms.
2907 void
2908 mono_set_signal_chaining (gboolean chain_signals)
2910 mono_do_signal_chaining = chain_signals;
2914 * mono_set_crash_chaining:
2916 * Enable/disable crash chaining due to signals. When a fatal signal is delivered and
2917 * Mono doesn't know how to handle it, it will invoke the crash handler. If chrash chaining
2918 * is enabled, it will first print its crash information and then try to chain with the native handler.
2920 void
2921 mono_set_crash_chaining (gboolean chain_crashes)
2923 mono_do_crash_chaining = chain_crashes;
2927 * mono_parse_options_from:
2928 * \param options string containing strings
2929 * \param ref_argc pointer to the \c argc variable that might be updated
2930 * \param ref_argv pointer to the \c argv string vector variable that might be updated
2932 * This function parses the contents of the \c MONO_ENV_OPTIONS
2933 * environment variable as if they were parsed by a command shell
2934 * splitting the contents by spaces into different elements of the
2935 * \p argv vector. This method supports quoting with both the " and '
2936 * characters. Inside quoting, spaces and tabs are significant,
2937 * otherwise, they are considered argument separators.
2939 * The \ character can be used to escape the next character which will
2940 * be added to the current element verbatim. Typically this is used
2941 * inside quotes. If the quotes are not balanced, this method
2943 * If the environment variable is empty, no changes are made
2944 * to the values pointed by \p ref_argc and \p ref_argv.
2946 * Otherwise the \p ref_argv is modified to point to a new array that contains
2947 * all the previous elements contained in the vector, plus the values parsed.
2948 * The \p argc is updated to match the new number of parameters.
2950 * \returns The value NULL is returned on success, otherwise a \c g_strdup allocated
2951 * string is returned (this is an alias to \c malloc under normal circumstances) that
2952 * contains the error message that happened during parsing.
2954 char *
2955 mono_parse_options_from (const char *options, int *ref_argc, char **ref_argv [])
2957 return mono_parse_options (options, ref_argc, ref_argv, TRUE);
2960 static void
2961 merge_parsed_options (GPtrArray *parsed_options, int *ref_argc, char **ref_argv [], gboolean prepend)
2963 int argc = *ref_argc;
2964 char **argv = *ref_argv;
2966 if (parsed_options->len > 0){
2967 int new_argc = parsed_options->len + argc;
2968 char **new_argv = g_new (char *, new_argc + 1);
2969 guint i;
2970 guint j;
2972 new_argv [0] = argv [0];
2974 i = 1;
2975 if (prepend){
2976 /* First the environment variable settings, to allow the command line options to override */
2977 for (i = 0; i < parsed_options->len; i++)
2978 new_argv [i+1] = (char *)g_ptr_array_index (parsed_options, i);
2979 i++;
2981 for (j = 1; j < argc; j++)
2982 new_argv [i++] = argv [j];
2983 if (!prepend){
2984 for (j = 0; j < parsed_options->len; j++)
2985 new_argv [i++] = (char *)g_ptr_array_index (parsed_options, j);
2987 new_argv [i] = NULL;
2989 *ref_argc = new_argc;
2990 *ref_argv = new_argv;
2994 static char *
2995 mono_parse_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
2997 GPtrArray *array = g_ptr_array_new ();
2998 GString *buffer = g_string_new ("");
2999 const char *p;
3000 gboolean in_quotes = FALSE;
3001 char quote_char = '\0';
3003 if (options == NULL)
3004 return NULL;
3006 for (p = options; *p; p++){
3007 switch (*p){
3008 case ' ': case '\t': case '\n':
3009 if (!in_quotes) {
3010 if (buffer->len != 0){
3011 g_ptr_array_add (array, g_strdup (buffer->str));
3012 g_string_truncate (buffer, 0);
3014 } else {
3015 g_string_append_c (buffer, *p);
3017 break;
3018 case '\\':
3019 if (p [1]){
3020 g_string_append_c (buffer, p [1]);
3021 p++;
3023 break;
3024 case '\'':
3025 case '"':
3026 if (in_quotes) {
3027 if (quote_char == *p)
3028 in_quotes = FALSE;
3029 else
3030 g_string_append_c (buffer, *p);
3031 } else {
3032 in_quotes = TRUE;
3033 quote_char = *p;
3035 break;
3036 default:
3037 g_string_append_c (buffer, *p);
3038 break;
3041 if (in_quotes)
3042 return g_strdup_printf ("Unmatched quotes in value: [%s]\n", options);
3044 if (buffer->len != 0)
3045 g_ptr_array_add (array, g_strdup (buffer->str));
3046 g_string_free (buffer, TRUE);
3048 merge_parsed_options (array, ref_argc, ref_argv, prepend);
3049 g_ptr_array_free (array, TRUE);
3051 return NULL;
3054 #if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
3055 #include <shellapi.h>
3057 static char *
3058 mono_win32_parse_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3060 int argc;
3061 gunichar2 **argv;
3062 gunichar2 *optionsw;
3064 if (!options)
3065 return NULL;
3067 GPtrArray *array = g_ptr_array_new ();
3068 optionsw = g_utf8_to_utf16 (options, -1, NULL, NULL, NULL);
3069 if (optionsw) {
3070 gunichar2 *p;
3071 gboolean in_quotes = FALSE;
3072 gunichar2 quote_char = L'\0';
3073 for (p = optionsw; *p; p++){
3074 switch (*p){
3075 case L'\n':
3076 if (!in_quotes)
3077 *p = L' ';
3078 break;
3079 case L'\'':
3080 case L'"':
3081 if (in_quotes) {
3082 if (quote_char == *p)
3083 in_quotes = FALSE;
3084 } else {
3085 in_quotes = TRUE;
3086 quote_char = *p;
3088 break;
3092 argv = CommandLineToArgvW (optionsw, &argc);
3093 if (argv) {
3094 for (int i = 0; i < argc; i++)
3095 g_ptr_array_add (array, g_utf16_to_utf8 (argv[i], -1, NULL, NULL, NULL));
3097 LocalFree (argv);
3100 g_free (optionsw);
3103 merge_parsed_options (array, ref_argc, ref_argv, prepend);
3104 g_ptr_array_free (array, TRUE);
3106 return NULL;
3109 static inline char *
3110 mono_parse_response_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3112 return mono_win32_parse_options (options, ref_argc, ref_argv, prepend);
3114 #else
3115 static inline char *
3116 mono_parse_response_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3118 return mono_parse_options (options, ref_argc, ref_argv, prepend);
3120 #endif
3123 * mono_parse_env_options:
3124 * \param ref_argc pointer to the \c argc variable that might be updated
3125 * \param ref_argv pointer to the \c argv string vector variable that might be updated
3127 * This function parses the contents of the \c MONO_ENV_OPTIONS
3128 * environment variable as if they were parsed by a command shell
3129 * splitting the contents by spaces into different elements of the
3130 * \p argv vector. This method supports quoting with both the " and '
3131 * characters. Inside quoting, spaces and tabs are significant,
3132 * otherwise, they are considered argument separators.
3134 * The \ character can be used to escape the next character which will
3135 * be added to the current element verbatim. Typically this is used
3136 * inside quotes. If the quotes are not balanced, this method
3138 * If the environment variable is empty, no changes are made
3139 * to the values pointed by \p ref_argc and \p ref_argv.
3141 * Otherwise the \p ref_argv is modified to point to a new array that contains
3142 * all the previous elements contained in the vector, plus the values parsed.
3143 * The \p argc is updated to match the new number of parameters.
3145 * If there is an error parsing, this method will terminate the process by
3146 * calling exit(1).
3148 * An alternative to this method that allows an arbitrary string to be parsed
3149 * and does not exit on error is the `api:mono_parse_options_from`.
3151 void
3152 mono_parse_env_options (int *ref_argc, char **ref_argv [])
3154 char *ret;
3156 char *env_options = g_getenv ("MONO_ENV_OPTIONS");
3157 if (env_options == NULL)
3158 return;
3159 ret = mono_parse_options_from (env_options, ref_argc, ref_argv);
3160 g_free (env_options);
3161 if (ret == NULL)
3162 return;
3163 fprintf (stderr, "%s", ret);
3164 exit (1);