Completely replace mono_error_ok with is_ok and make first external_only. (#16217)
[mono-project.git] / mono / mini / driver.c
blobc70c2f2da15972abf52b4b57aeceaee03ae7ea8a
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/image-internals.h>
27 #include <mono/metadata/loader.h>
28 #include <mono/metadata/tabledefs.h>
29 #include <mono/metadata/class.h>
30 #include <mono/metadata/object.h>
31 #include <mono/metadata/exception.h>
32 #include <mono/metadata/opcodes.h>
33 #include <mono/metadata/mono-endian.h>
34 #include <mono/metadata/tokentype.h>
35 #include <mono/metadata/reflection-internals.h>
36 #include <mono/metadata/tabledefs.h>
37 #include <mono/metadata/threads.h>
38 #include <mono/metadata/marshal.h>
39 #include <mono/metadata/appdomain.h>
40 #include <mono/metadata/debug-helpers.h>
41 #include <mono/metadata/profiler-private.h>
42 #include <mono/metadata/mono-config.h>
43 #include <mono/metadata/environment.h>
44 #include <mono/metadata/verify.h>
45 #include <mono/metadata/verify-internals.h>
46 #include <mono/metadata/mono-debug.h>
47 #include <mono/metadata/security-manager.h>
48 #include <mono/metadata/security-core-clr.h>
49 #include <mono/metadata/gc-internals.h>
50 #include <mono/metadata/coree.h>
51 #include <mono/metadata/attach.h>
52 #include <mono/metadata/w32process.h>
53 #include "mono/utils/mono-counters.h"
54 #include "mono/utils/mono-hwcap.h"
55 #include "mono/utils/mono-logger-internals.h"
56 #include "mono/metadata/w32handle.h"
57 #include "mono/metadata/callspec.h"
58 #include "mono/metadata/custom-attrs-internals.h"
60 #include "mini.h"
61 #include "jit.h"
62 #include "aot-compiler.h"
63 #include "aot-runtime.h"
64 #include "mini-runtime.h"
65 #include "interp/interp.h"
67 #include <string.h>
68 #include <ctype.h>
69 #include <locale.h>
70 #include "version.h"
71 #include "debugger-agent.h"
72 #if TARGET_OSX
73 # include <sys/resource.h>
74 #endif
76 static FILE *mini_stats_fd;
78 static void mini_usage (void);
79 static void mono_runtime_set_execution_mode (MonoEEMode mode);
80 static void mono_runtime_set_execution_mode_full (MonoEEMode mode, gboolean override);
81 static int mono_jit_exec_internal (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[]);
83 #ifdef HOST_WIN32
84 /* Need this to determine whether to detach console */
85 #include <mono/metadata/cil-coff.h>
86 /* This turns off command line globbing under win32 */
87 int _CRT_glob = 0;
88 #endif
90 typedef void (*OptFunc) (const char *p);
92 #undef OPTFLAG
94 // This, instead of an array of pointers, to optimize away a pointer and a relocation per string.
95 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
96 #define MSGSTRFIELD1(line) str##line
98 static const struct msgstr_t {
99 #define OPTFLAG(id,shift,name,desc) char MSGSTRFIELD(__LINE__) [sizeof (name) + sizeof (desc)];
100 #include "optflags-def.h"
101 #undef OPTFLAG
102 } opstr = {
103 #define OPTFLAG(id,shift,name,desc) name "\0" desc,
104 #include "optflags-def.h"
105 #undef OPTFLAG
107 static const gint16 opt_names [] = {
108 #define OPTFLAG(id,shift,name,desc) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
109 #include "optflags-def.h"
110 #undef OPTFLAG
113 #define optflag_get_name(id) ((const char*)&opstr + opt_names [(id)])
114 #define optflag_get_desc(id) (optflag_get_name(id) + 1 + strlen (optflag_get_name(id)))
116 #define DEFAULT_OPTIMIZATIONS ( \
117 MONO_OPT_PEEPHOLE | \
118 MONO_OPT_CFOLD | \
119 MONO_OPT_INLINE | \
120 MONO_OPT_CONSPROP | \
121 MONO_OPT_COPYPROP | \
122 MONO_OPT_DEADCE | \
123 MONO_OPT_BRANCH | \
124 MONO_OPT_LINEARS | \
125 MONO_OPT_INTRINS | \
126 MONO_OPT_LOOP | \
127 MONO_OPT_EXCEPTION | \
128 MONO_OPT_CMOV | \
129 MONO_OPT_GSHARED | \
130 MONO_OPT_SIMD | \
131 MONO_OPT_ALIAS_ANALYSIS | \
132 MONO_OPT_AOT | \
133 MONO_OPT_FLOAT32)
135 #define EXCLUDED_FROM_ALL (MONO_OPT_SHARED | MONO_OPT_PRECOMP | MONO_OPT_UNSAFE | MONO_OPT_GSHAREDVT)
137 static char *mono_parse_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend);
138 static char *mono_parse_response_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend);
140 static guint32
141 parse_optimizations (guint32 opt, const char* p, gboolean cpu_opts)
143 guint32 exclude = 0;
144 const char *n;
145 int i, invert;
146 char **parts, **ptr;
148 /* Initialize the hwcap module if necessary. */
149 mono_hwcap_init ();
151 /* call out to cpu detection code here that sets the defaults ... */
152 if (cpu_opts) {
153 #ifndef MONO_CROSS_COMPILE
154 opt |= mono_arch_cpu_optimizations (&exclude);
155 opt &= ~exclude;
156 #endif
158 if (!p)
159 return opt;
161 parts = g_strsplit (p, ",", -1);
162 for (ptr = parts; ptr && *ptr; ptr ++) {
163 char *arg = *ptr;
164 char *p = arg;
166 if (*p == '-') {
167 p++;
168 invert = TRUE;
169 } else {
170 invert = FALSE;
172 for (i = 0; i < G_N_ELEMENTS (opt_names) && optflag_get_name (i); ++i) {
173 n = optflag_get_name (i);
174 if (!strcmp (p, n)) {
175 if (invert)
176 opt &= ~ (1 << i);
177 else
178 opt |= 1 << i;
179 break;
182 if (i == G_N_ELEMENTS (opt_names) || !optflag_get_name (i)) {
183 if (strncmp (p, "all", 3) == 0) {
184 if (invert)
185 opt = 0;
186 else
187 opt = ~(EXCLUDED_FROM_ALL | exclude);
188 } else {
189 fprintf (stderr, "Invalid optimization name `%s'\n", p);
190 exit (1);
194 g_free (arg);
196 g_free (parts);
198 return opt;
201 static gboolean
202 parse_debug_options (const char* p)
204 MonoDebugOptions *opt = mini_get_debug_options ();
206 do {
207 if (!*p) {
208 fprintf (stderr, "Syntax error; expected debug option name\n");
209 return FALSE;
212 if (!strncmp (p, "casts", 5)) {
213 opt->better_cast_details = TRUE;
214 p += 5;
215 } else if (!strncmp (p, "mdb-optimizations", 17)) {
216 opt->mdb_optimizations = TRUE;
217 p += 17;
218 } else if (!strncmp (p, "gdb", 3)) {
219 opt->gdb = TRUE;
220 p += 3;
221 } else {
222 fprintf (stderr, "Invalid debug option `%s', use --help-debug for details\n", p);
223 return FALSE;
226 if (*p == ',') {
227 p++;
228 if (!*p) {
229 fprintf (stderr, "Syntax error; expected debug option name\n");
230 return FALSE;
233 } while (*p);
235 return TRUE;
238 typedef struct {
239 const char name [6];
240 const char desc [18];
241 MonoGraphOptions value;
242 } GraphName;
244 static const GraphName
245 graph_names [] = {
246 {"cfg", "Control Flow", MONO_GRAPH_CFG},
247 {"dtree", "Dominator Tree", MONO_GRAPH_DTREE},
248 {"code", "CFG showing code", MONO_GRAPH_CFG_CODE},
249 {"ssa", "CFG after SSA", MONO_GRAPH_CFG_SSA},
250 {"optc", "CFG after IR opts", MONO_GRAPH_CFG_OPTCODE}
253 static MonoGraphOptions
254 mono_parse_graph_options (const char* p)
256 const char *n;
257 int i, len;
259 for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
260 n = graph_names [i].name;
261 len = strlen (n);
262 if (strncmp (p, n, len) == 0)
263 return graph_names [i].value;
266 fprintf (stderr, "Invalid graph name provided: %s\n", p);
267 exit (1);
271 * mono_parse_default_optimizations:
274 mono_parse_default_optimizations (const char* p)
276 guint32 opt;
278 opt = parse_optimizations (DEFAULT_OPTIMIZATIONS, p, TRUE);
279 return opt;
282 char*
283 mono_opt_descr (guint32 flags) {
284 GString *str = g_string_new ("");
285 int i, need_comma;
287 need_comma = 0;
288 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
289 if (flags & (1 << i) && optflag_get_name (i)) {
290 if (need_comma)
291 g_string_append_c (str, ',');
292 g_string_append (str, optflag_get_name (i));
293 need_comma = 1;
296 return g_string_free (str, FALSE);
299 static const guint32
300 opt_sets [] = {
302 MONO_OPT_PEEPHOLE,
303 MONO_OPT_BRANCH,
304 MONO_OPT_CFOLD,
305 MONO_OPT_FCMOV,
306 MONO_OPT_ALIAS_ANALYSIS,
307 #ifdef MONO_ARCH_SIMD_INTRINSICS
308 MONO_OPT_SIMD | MONO_OPT_INTRINS,
309 MONO_OPT_SSE2,
310 MONO_OPT_SIMD | MONO_OPT_SSE2 | MONO_OPT_INTRINS,
311 #endif
312 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS,
313 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS | MONO_OPT_ALIAS_ANALYSIS,
314 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS,
315 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP,
316 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_CFOLD,
317 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE,
318 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_ALIAS_ANALYSIS,
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,
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_TAILCALL,
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_SSA,
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,
323 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_EXCEPTION | MONO_OPT_CMOV,
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_EXCEPTION | MONO_OPT_ABCREM,
325 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_ABCREM,
326 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,
327 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,
328 DEFAULT_OPTIMIZATIONS,
331 typedef int (*TestMethod) (void);
333 #if 0
334 static void
335 domain_dump_native_code (MonoDomain *domain) {
336 // need to poke into the domain, move to metadata/domain.c
337 // need to empty jit_info_table and code_mp
339 #endif
341 static gboolean do_regression_retries;
342 static int regression_test_skip_index;
345 static gboolean
346 method_should_be_regression_tested (MonoMethod *method, gboolean interp)
348 ERROR_DECL (error);
350 if (strncmp (method->name, "test_", 5) != 0)
351 return FALSE;
353 static gboolean filter_method_init = FALSE;
354 static const char *filter_method = NULL;
356 if (!filter_method_init) {
357 filter_method = g_getenv ("REGRESSION_FILTER_METHOD");
358 filter_method_init = TRUE;
361 if (filter_method) {
362 const char *name = filter_method;
364 if ((strchr (name, '.') > name) || strchr (name, ':')) {
365 MonoMethodDesc *desc = mono_method_desc_new (name, TRUE);
366 gboolean res = mono_method_desc_full_match (desc, method);
367 mono_method_desc_free (desc);
368 return res;
369 } else {
370 return strcmp (method->name, name) == 0;
374 MonoCustomAttrInfo* ainfo = mono_custom_attrs_from_method_checked (method, error);
375 mono_error_cleanup (error);
376 if (!ainfo)
377 return TRUE;
379 int j;
380 for (j = 0; j < ainfo->num_attrs; ++j) {
381 MonoCustomAttrEntry *centry = &ainfo->attrs [j];
382 if (centry->ctor == NULL)
383 continue;
385 MonoClass *klass = centry->ctor->klass;
386 if (strcmp (m_class_get_name (klass), "CategoryAttribute") || mono_method_signature_internal (centry->ctor)->param_count != 1)
387 continue;
389 gpointer *typed_args, *named_args;
390 int num_named_args;
391 CattrNamedArg *arginfo;
393 mono_reflection_create_custom_attr_data_args_noalloc (
394 mono_defaults.corlib, centry->ctor, centry->data, centry->data_size,
395 &typed_args, &named_args, &num_named_args, &arginfo, error);
396 if (!is_ok (error))
397 continue;
399 char *utf8_str = (char*)(void*)typed_args[0]; //this points into image memory that is constant
400 g_free (typed_args);
401 g_free (named_args);
402 g_free (arginfo);
404 if (interp && !strcmp (utf8_str, "!INTERPRETER")) {
405 g_print ("skip %s...\n", method->name);
406 return FALSE;
409 #if HOST_WASM
410 if (!strcmp (utf8_str, "!WASM")) {
411 g_print ("skip %s...\n", method->name);
412 return FALSE;
414 #endif
415 if (mono_aot_mode == MONO_AOT_MODE_FULL && !strcmp (utf8_str, "!FULLAOT")) {
416 g_print ("skip %s...\n", method->name);
417 return FALSE;
420 if ((mono_aot_mode == MONO_AOT_MODE_INTERP_LLVMONLY || mono_aot_mode == MONO_AOT_MODE_LLVMONLY) && !strcmp (utf8_str, "!BITCODE")) {
421 g_print ("skip %s...\n", method->name);
422 return FALSE;
426 return TRUE;
429 static void
430 mini_regression_step (MonoImage *image, int verbose, int *total_run, int *total,
431 guint32 opt_flags,
432 GTimer *timer, MonoDomain *domain)
434 int result, expected, failed, cfailed, run, code_size;
435 double elapsed, comp_time, start_time;
436 char *n;
437 int i;
439 mono_set_defaults (verbose, opt_flags);
440 n = mono_opt_descr (opt_flags);
441 g_print ("Test run: image=%s, opts=%s\n", mono_image_get_filename (image), n);
442 g_free (n);
443 cfailed = failed = run = code_size = 0;
444 comp_time = elapsed = 0.0;
445 int local_skip_index = 0;
447 /* fixme: ugly hack - delete all previously compiled methods */
448 if (domain_jit_info (domain)) {
449 g_hash_table_destroy (domain_jit_info (domain)->jit_trampoline_hash);
450 domain_jit_info (domain)->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
451 mono_internal_hash_table_destroy (&(domain->jit_code_hash));
452 mono_jit_code_hash_init (&(domain->jit_code_hash));
455 g_timer_start (timer);
456 if (mini_stats_fd)
457 fprintf (mini_stats_fd, "[");
458 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
459 ERROR_DECL (error);
460 MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
461 if (!method) {
462 mono_error_cleanup (error); /* FIXME don't swallow the error */
463 continue;
465 if (method_should_be_regression_tested (method, FALSE)) {
466 MonoCompile *cfg = NULL;
467 TestMethod func = NULL;
469 expected = atoi (method->name + 5);
470 run++;
471 start_time = g_timer_elapsed (timer, NULL);
473 #ifdef DISABLE_JIT
474 #ifdef MONO_USE_AOT_COMPILER
475 ERROR_DECL (error);
476 func = (TestMethod)mono_aot_get_method (mono_get_root_domain (), method, error);
477 mono_error_cleanup (error);
478 #else
479 g_error ("No JIT or AOT available, regression testing not possible!")
480 #endif
482 #else
483 comp_time -= start_time;
484 cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, opt_flags), mono_get_root_domain (), JIT_FLAG_RUN_CCTORS, 0, -1);
485 comp_time += g_timer_elapsed (timer, NULL);
486 if (cfg->exception_type == MONO_EXCEPTION_NONE) {
487 #ifdef MONO_USE_AOT_COMPILER
488 ERROR_DECL (error);
489 func = (TestMethod)mono_aot_get_method (mono_get_root_domain (), method, error);
490 mono_error_cleanup (error);
491 if (!func)
492 func = (TestMethod)(gpointer)cfg->native_code;
493 #else
494 func = (TestMethod)(gpointer)cfg->native_code;
495 #endif
496 func = (TestMethod)mono_create_ftnptr (mono_get_root_domain (), (gpointer)func);
498 #endif
500 if (func) {
501 if (do_regression_retries) {
502 ++local_skip_index;
504 if(local_skip_index <= regression_test_skip_index)
505 continue;
506 ++regression_test_skip_index;
509 if (verbose >= 2)
510 g_print ("Running '%s' ...\n", method->name);
512 #if HOST_WASM
513 //WASM AOT injects dummy args and we must call with exact signatures
514 int (*func_2)(int) = (int (*)(int))(void*)func;
515 result = func_2 (-1);
516 #else
517 result = func ();
518 #endif
519 if (result != expected) {
520 failed++;
521 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
523 if (cfg) {
524 code_size += cfg->code_len;
525 mono_destroy_compile (cfg);
527 } else {
528 cfailed++;
529 g_print ("Test '%s' failed compilation.\n", method->name);
531 if (mini_stats_fd)
532 fprintf (mini_stats_fd, "%f, ",
533 g_timer_elapsed (timer, NULL) - start_time);
536 if (mini_stats_fd)
537 fprintf (mini_stats_fd, "],\n");
538 g_timer_stop (timer);
539 elapsed = g_timer_elapsed (timer, NULL);
540 if (failed > 0 || cfailed > 0){
541 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n",
542 run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
543 } else {
544 g_print ("Results: total tests: %d, all pass \n", run);
547 g_print ("Elapsed time: %f secs (%f, %f), Code size: %d\n\n", elapsed,
548 elapsed - comp_time, comp_time, code_size);
549 *total += failed + cfailed;
550 *total_run += run;
553 static int
554 mini_regression (MonoImage *image, int verbose, int *total_run)
556 guint32 i, opt;
557 MonoMethod *method;
558 char *n;
559 GTimer *timer = g_timer_new ();
560 MonoDomain *domain = mono_domain_get ();
561 guint32 exclude = 0;
562 int total;
564 /* Note: mono_hwcap_init () called in mono_init () before we get here. */
565 mono_arch_cpu_optimizations (&exclude);
567 if (mini_stats_fd) {
568 fprintf (mini_stats_fd, "$stattitle = \'Mono Benchmark Results (various optimizations)\';\n");
570 fprintf (mini_stats_fd, "$graph->set_legend(qw(");
571 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); opt++) {
572 guint32 opt_flags = opt_sets [opt];
573 n = mono_opt_descr (opt_flags);
574 if (!n [0])
575 n = (char *)"none";
576 if (opt)
577 fprintf (mini_stats_fd, " ");
578 fprintf (mini_stats_fd, "%s", n);
582 fprintf (mini_stats_fd, "));\n");
584 fprintf (mini_stats_fd, "@data = (\n");
585 fprintf (mini_stats_fd, "[");
588 /* load the metadata */
589 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
590 ERROR_DECL (error);
591 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
592 if (!method) {
593 mono_error_cleanup (error);
594 continue;
596 mono_class_init_internal (method->klass);
598 if (!strncmp (method->name, "test_", 5) && mini_stats_fd) {
599 fprintf (mini_stats_fd, "\"%s\",", method->name);
602 if (mini_stats_fd)
603 fprintf (mini_stats_fd, "],\n");
606 total = 0;
607 *total_run = 0;
608 if (mono_do_single_method_regression) {
609 GSList *iter;
611 mini_regression_step (image, verbose, total_run, &total,
613 timer, domain);
614 if (total)
615 return total;
616 g_print ("Single method regression: %d methods\n", g_slist_length (mono_single_method_list));
618 for (iter = mono_single_method_list; iter; iter = g_slist_next (iter)) {
619 char *method_name;
621 mono_current_single_method = (MonoMethod *)iter->data;
623 method_name = mono_method_full_name (mono_current_single_method, TRUE);
624 g_print ("Current single method: %s\n", method_name);
625 g_free (method_name);
627 mini_regression_step (image, verbose, total_run, &total,
629 timer, domain);
630 if (total)
631 return total;
633 } else {
634 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); ++opt) {
635 /* builtin-types.cs & aot-tests.cs need OPT_INTRINS enabled */
636 if (!strcmp ("builtin-types", image->assembly_name) || !strcmp ("aot-tests", image->assembly_name))
637 if (!(opt_sets [opt] & MONO_OPT_INTRINS))
638 continue;
640 //we running in AOT only, it makes no sense to try multiple flags
641 if ((mono_aot_mode == MONO_AOT_MODE_FULL || mono_aot_mode == MONO_AOT_MODE_LLVMONLY) && opt_sets [opt] != DEFAULT_OPTIMIZATIONS) {
642 continue;
645 mini_regression_step (image, verbose, total_run, &total,
646 opt_sets [opt] & ~exclude,
647 timer, domain);
651 if (mini_stats_fd) {
652 fprintf (mini_stats_fd, ");\n");
653 fflush (mini_stats_fd);
656 g_timer_destroy (timer);
657 return total;
660 static int
661 mini_regression_list (int verbose, int count, char *images [])
663 int i, total, total_run, run;
664 MonoAssembly *ass;
666 total_run = total = 0;
667 for (i = 0; i < count; ++i) {
668 MonoAssemblyOpenRequest req;
669 mono_assembly_request_prepare (&req.request, sizeof (req), MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_get_root_domain ()));
670 ass = mono_assembly_request_open (images [i], &req, NULL);
671 if (!ass) {
672 g_warning ("failed to load assembly: %s", images [i]);
673 continue;
675 total += mini_regression (mono_assembly_get_image_internal (ass), verbose, &run);
676 total_run += run;
678 if (total > 0){
679 g_print ("Overall results: tests: %d, failed: %d, opt combinations: %d (pass: %.2f%%)\n",
680 total_run, total, (int)G_N_ELEMENTS (opt_sets), 100.0*(total_run-total)/total_run);
681 } else {
682 g_print ("Overall results: tests: %d, 100%% pass, opt combinations: %d\n",
683 total_run, (int)G_N_ELEMENTS (opt_sets));
686 return total;
689 static void
690 interp_regression_step (MonoImage *image, int verbose, int *total_run, int *total, GTimer *timer, MonoDomain *domain)
692 int result, expected, failed, cfailed, run;
693 double elapsed, transform_time;
694 int i;
695 MonoObject *result_obj;
696 int local_skip_index = 0;
698 g_print ("Test run: image=%s\n", mono_image_get_filename (image));
699 cfailed = failed = run = 0;
700 transform_time = elapsed = 0.0;
702 g_timer_start (timer);
703 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
704 ERROR_DECL (error);
705 MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
706 if (!method) {
707 mono_error_cleanup (error); /* FIXME don't swallow the error */
708 continue;
711 if (method_should_be_regression_tested (method, TRUE)) {
712 ERROR_DECL (interp_error);
713 MonoObject *exc = NULL;
715 if (do_regression_retries) {
716 ++local_skip_index;
718 if(local_skip_index <= regression_test_skip_index)
719 continue;
720 ++regression_test_skip_index;
723 result_obj = mini_get_interp_callbacks ()->runtime_invoke (method, NULL, NULL, &exc, interp_error);
724 if (!is_ok (interp_error)) {
725 cfailed++;
726 g_print ("Test '%s' execution failed.\n", method->name);
727 } else if (exc != NULL) {
728 g_print ("Exception in Test '%s' occured:\n", method->name);
729 mono_object_describe (exc);
730 run++;
731 failed++;
732 } else {
733 result = *(gint32 *) mono_object_unbox_internal (result_obj);
734 expected = atoi (method->name + 5); // FIXME: oh no.
735 run++;
737 if (result != expected) {
738 failed++;
739 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
744 g_timer_stop (timer);
745 elapsed = g_timer_elapsed (timer, NULL);
746 if (failed > 0 || cfailed > 0){
747 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n",
748 run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
749 } else {
750 g_print ("Results: total tests: %d, all pass \n", run);
753 g_print ("Elapsed time: %f secs (%f, %f)\n\n", elapsed,
754 elapsed - transform_time, transform_time);
755 *total += failed + cfailed;
756 *total_run += run;
759 static int
760 interp_regression (MonoImage *image, int verbose, int *total_run)
762 MonoMethod *method;
763 GTimer *timer = g_timer_new ();
764 MonoDomain *domain = mono_domain_get ();
765 guint32 i;
766 int total;
768 /* load the metadata */
769 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
770 ERROR_DECL (error);
771 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
772 if (!method) {
773 mono_error_cleanup (error);
774 continue;
776 mono_class_init_internal (method->klass);
779 total = 0;
780 *total_run = 0;
781 interp_regression_step (image, verbose, total_run, &total, timer, domain);
783 g_timer_destroy (timer);
784 return total;
787 /* TODO: merge this code with the regression harness of the JIT */
788 static int
789 mono_interp_regression_list (int verbose, int count, char *images [])
791 int i, total, total_run, run;
793 total_run = total = 0;
794 for (i = 0; i < count; ++i) {
795 MonoAssemblyOpenRequest req;
796 mono_assembly_request_prepare (&req.request, sizeof (req), MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_get_root_domain ()));
797 MonoAssembly *ass = mono_assembly_request_open (images [i], &req, NULL);
798 if (!ass) {
799 g_warning ("failed to load assembly: %s", images [i]);
800 continue;
802 total += interp_regression (mono_assembly_get_image_internal (ass), verbose, &run);
803 total_run += run;
805 if (total > 0) {
806 g_print ("Overall results: tests: %d, failed: %d (pass: %.2f%%)\n", total_run, total, 100.0*(total_run-total)/total_run);
807 } else {
808 g_print ("Overall results: tests: %d, 100%% pass\n", total_run);
811 return total;
815 #ifdef MONO_JIT_INFO_TABLE_TEST
816 typedef struct _JitInfoData
818 guint start;
819 guint length;
820 MonoJitInfo *ji;
821 struct _JitInfoData *next;
822 } JitInfoData;
824 typedef struct
826 guint start;
827 guint length;
828 int num_datas;
829 JitInfoData *data;
830 } Region;
832 typedef struct
834 int num_datas;
835 int num_regions;
836 Region *regions;
837 int num_frees;
838 JitInfoData *frees;
839 } ThreadData;
841 static int num_threads;
842 static ThreadData *thread_datas;
843 static MonoDomain *test_domain;
845 static JitInfoData*
846 alloc_random_data (Region *region)
848 JitInfoData **data;
849 JitInfoData *prev;
850 guint prev_end;
851 guint next_start;
852 guint max_len;
853 JitInfoData *d;
854 int num_retries = 0;
855 int pos, i;
857 restart:
858 prev = NULL;
859 data = &region->data;
860 pos = random () % (region->num_datas + 1);
861 i = 0;
862 while (*data != NULL) {
863 if (i++ == pos)
864 break;
865 prev = *data;
866 data = &(*data)->next;
869 if (prev == NULL)
870 g_assert (*data == region->data);
871 else
872 g_assert (prev->next == *data);
874 if (prev == NULL)
875 prev_end = region->start;
876 else
877 prev_end = prev->start + prev->length;
879 if (*data == NULL)
880 next_start = region->start + region->length;
881 else
882 next_start = (*data)->start;
884 g_assert (prev_end <= next_start);
886 max_len = next_start - prev_end;
887 if (max_len < 128) {
888 if (++num_retries >= 10)
889 return NULL;
890 goto restart;
892 if (max_len > 1024)
893 max_len = 1024;
895 d = g_new0 (JitInfoData, 1);
896 d->start = prev_end + random () % (max_len / 2);
897 d->length = random () % MIN (max_len, next_start - d->start) + 1;
899 g_assert (d->start >= prev_end && d->start + d->length <= next_start);
901 d->ji = g_new0 (MonoJitInfo, 1);
902 d->ji->d.method = (MonoMethod*) 0xABadBabe;
903 d->ji->code_start = (gpointer)(gulong) d->start;
904 d->ji->code_size = d->length;
905 d->ji->cas_inited = 1; /* marks an allocated jit info */
907 d->next = *data;
908 *data = d;
910 ++region->num_datas;
912 return d;
915 static JitInfoData**
916 choose_random_data (Region *region)
918 int n;
919 int i;
920 JitInfoData **d;
922 g_assert (region->num_datas > 0);
924 n = random () % region->num_datas;
926 for (d = &region->data, i = 0;
927 i < n;
928 d = &(*d)->next, ++i)
931 return d;
934 static Region*
935 choose_random_region (ThreadData *td)
937 return &td->regions [random () % td->num_regions];
940 static ThreadData*
941 choose_random_thread (void)
943 return &thread_datas [random () % num_threads];
946 static void
947 free_jit_info_data (ThreadData *td, JitInfoData *free)
949 free->next = td->frees;
950 td->frees = free;
952 if (++td->num_frees >= 1000) {
953 int i;
955 for (i = 0; i < 500; ++i)
956 free = free->next;
958 while (free->next != NULL) {
959 JitInfoData *next = free->next->next;
961 //g_free (free->next->ji);
962 g_free (free->next);
963 free->next = next;
965 --td->num_frees;
970 #define NUM_THREADS 8
971 #define REGIONS_PER_THREAD 10
972 #define REGION_SIZE 0x10000
974 #define MAX_ADDR (REGION_SIZE * REGIONS_PER_THREAD * NUM_THREADS)
976 #define MODE_ALLOC 1
977 #define MODE_FREE 2
979 static void
980 test_thread_func (gpointer void_arg)
982 ThreadData* td = (ThreadData*)void_arg;
983 int mode = MODE_ALLOC;
984 int i = 0;
985 gulong lookup_successes = 0, lookup_failures = 0;
986 MonoDomain *domain = test_domain;
987 int thread_num = (int)(td - thread_datas);
988 gboolean modify_thread = thread_num < NUM_THREADS / 2; /* only half of the threads modify the table */
990 for (;;) {
991 int alloc;
992 int lookup = 1;
994 if (td->num_datas == 0) {
995 lookup = 0;
996 alloc = 1;
997 } else if (modify_thread && random () % 1000 < 5) {
998 lookup = 0;
999 if (mode == MODE_ALLOC)
1000 alloc = (random () % 100) < 70;
1001 else if (mode == MODE_FREE)
1002 alloc = (random () % 100) < 30;
1005 if (lookup) {
1006 /* modify threads sometimes look up their own jit infos */
1007 if (modify_thread && random () % 10 < 5) {
1008 Region *region = choose_random_region (td);
1010 if (region->num_datas > 0) {
1011 JitInfoData **data = choose_random_data (region);
1012 guint pos = (*data)->start + random () % (*data)->length;
1013 MonoJitInfo *ji;
1015 ji = mono_jit_info_table_find (domain, (char*)(gsize)pos);
1017 g_assert (ji->cas_inited);
1018 g_assert ((*data)->ji == ji);
1020 } else {
1021 int pos = random () % MAX_ADDR;
1022 char *addr = (char*)(uintptr_t)pos;
1023 MonoJitInfo *ji;
1025 ji = mono_jit_info_table_find (domain, addr);
1028 * FIXME: We are actually not allowed
1029 * to do this. By the time we examine
1030 * the ji another thread might already
1031 * have removed it.
1033 if (ji != NULL) {
1034 g_assert (addr >= (char*)ji->code_start && addr < (char*)ji->code_start + ji->code_size);
1035 ++lookup_successes;
1036 } else
1037 ++lookup_failures;
1039 } else if (alloc) {
1040 JitInfoData *data = alloc_random_data (choose_random_region (td));
1042 if (data != NULL) {
1043 mono_jit_info_table_add (domain, data->ji);
1045 ++td->num_datas;
1047 } else {
1048 Region *region = choose_random_region (td);
1050 if (region->num_datas > 0) {
1051 JitInfoData **data = choose_random_data (region);
1052 JitInfoData *free;
1054 mono_jit_info_table_remove (domain, (*data)->ji);
1056 //(*data)->ji->cas_inited = 0; /* marks a free jit info */
1058 free = *data;
1059 *data = (*data)->next;
1061 free_jit_info_data (td, free);
1063 --region->num_datas;
1064 --td->num_datas;
1068 if (++i % 100000 == 0) {
1069 int j;
1070 g_print ("num datas %d (%ld - %ld): %d", (int)(td - thread_datas),
1071 lookup_successes, lookup_failures, td->num_datas);
1072 for (j = 0; j < td->num_regions; ++j)
1073 g_print (" %d", td->regions [j].num_datas);
1074 g_print ("\n");
1077 if (td->num_datas < 100)
1078 mode = MODE_ALLOC;
1079 else if (td->num_datas > 2000)
1080 mode = MODE_FREE;
1085 static void
1086 small_id_thread_func (gpointer arg)
1088 MonoThread *thread = mono_thread_current ();
1089 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1091 g_print ("my small id is %d\n", (int)thread->small_id);
1092 mono_hazard_pointer_clear (hp, 1);
1093 sleep (3);
1094 g_print ("done %d\n", (int)thread->small_id);
1098 static void
1099 jit_info_table_test (MonoDomain *domain)
1101 ERROR_DECL (error);
1102 int i;
1104 g_print ("testing jit_info_table\n");
1106 num_threads = NUM_THREADS;
1107 thread_datas = g_new0 (ThreadData, num_threads);
1109 for (i = 0; i < num_threads; ++i) {
1110 int j;
1112 thread_datas [i].num_regions = REGIONS_PER_THREAD;
1113 thread_datas [i].regions = g_new0 (Region, REGIONS_PER_THREAD);
1115 for (j = 0; j < REGIONS_PER_THREAD; ++j) {
1116 thread_datas [i].regions [j].start = (num_threads * j + i) * REGION_SIZE;
1117 thread_datas [i].regions [j].length = REGION_SIZE;
1121 test_domain = domain;
1124 for (i = 0; i < 72; ++i)
1125 mono_thread_create (domain, small_id_thread_func, NULL);
1127 sleep (2);
1130 for (i = 0; i < num_threads; ++i) {
1131 mono_thread_create_checked (domain, (gpointer)test_thread_func, &thread_datas [i], error);
1132 mono_error_assert_ok (error);
1135 #endif
1137 enum {
1138 DO_BENCH,
1139 DO_REGRESSION,
1140 DO_SINGLE_METHOD_REGRESSION,
1141 DO_COMPILE,
1142 DO_EXEC,
1143 DO_DRAW,
1144 DO_DEBUGGER
1147 typedef struct CompileAllThreadArgs {
1148 MonoAssembly *ass;
1149 int verbose;
1150 guint32 opts;
1151 guint32 recompilation_times;
1152 } CompileAllThreadArgs;
1154 static void
1155 compile_all_methods_thread_main_inner (CompileAllThreadArgs *args)
1157 MonoAssembly *ass = args->ass;
1158 int verbose = args->verbose;
1159 MonoImage *image = mono_assembly_get_image_internal (ass);
1160 MonoMethod *method;
1161 MonoCompile *cfg;
1162 int i, count = 0, fail_count = 0;
1164 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
1165 ERROR_DECL (error);
1166 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1167 MonoMethodSignature *sig;
1169 if (mono_metadata_has_generic_params (image, token))
1170 continue;
1172 method = mono_get_method_checked (image, token, NULL, NULL, error);
1173 if (!method) {
1174 mono_error_cleanup (error); /* FIXME don't swallow the error */
1175 continue;
1177 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1178 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1179 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1180 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1181 continue;
1183 if (mono_class_is_gtd (method->klass))
1184 continue;
1185 sig = mono_method_signature_internal (method);
1186 if (!sig) {
1187 char * desc = mono_method_full_name (method, TRUE);
1188 g_print ("Could not retrieve method signature for %s\n", desc);
1189 g_free (desc);
1190 fail_count ++;
1191 continue;
1194 if (sig->has_type_parameters)
1195 continue;
1197 count++;
1198 if (verbose) {
1199 char * desc = mono_method_full_name (method, TRUE);
1200 g_print ("Compiling %d %s\n", count, desc);
1201 g_free (desc);
1203 if (mono_use_interpreter) {
1204 mini_get_interp_callbacks ()->create_method_pointer (method, TRUE, error);
1205 // FIXME There are a few failures due to DllNotFoundException related to System.Native
1206 if (verbose && !is_ok (error))
1207 g_print ("Compilation of %s failed\n", mono_method_full_name (method, TRUE));
1208 } else {
1209 cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, args->opts), mono_get_root_domain (), (JitFlags)JIT_FLAG_DISCARD_RESULTS, 0, -1);
1210 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
1211 const char *msg = cfg->exception_message;
1212 if (cfg->exception_type == MONO_EXCEPTION_MONO_ERROR)
1213 msg = mono_error_get_message (&cfg->error);
1214 g_print ("Compilation of %s failed with exception '%s':\n", mono_method_full_name (cfg->method, TRUE), msg);
1215 fail_count ++;
1217 mono_destroy_compile (cfg);
1221 if (fail_count)
1222 exit (1);
1225 static void
1226 compile_all_methods_thread_main (gpointer void_args)
1228 CompileAllThreadArgs *args = (CompileAllThreadArgs*)void_args;
1229 guint32 i;
1230 for (i = 0; i < args->recompilation_times; ++i)
1231 compile_all_methods_thread_main_inner (args);
1234 static void
1235 compile_all_methods (MonoAssembly *ass, int verbose, guint32 opts, guint32 recompilation_times)
1237 ERROR_DECL (error);
1238 CompileAllThreadArgs args;
1240 args.ass = ass;
1241 args.verbose = verbose;
1242 args.opts = opts;
1243 args.recompilation_times = recompilation_times;
1246 * Need to create a mono thread since compilation might trigger
1247 * running of managed code.
1249 mono_thread_create_checked (mono_domain_get (), (gpointer)compile_all_methods_thread_main, &args, error);
1250 mono_error_assert_ok (error);
1252 mono_thread_manage ();
1256 * mono_jit_exec:
1257 * \param assembly reference to an assembly
1258 * \param argc argument count
1259 * \param argv argument vector
1260 * Start execution of a program.
1262 int
1263 mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
1265 int rv;
1266 MONO_ENTER_GC_UNSAFE;
1267 rv = mono_jit_exec_internal (domain, assembly, argc, argv);
1268 MONO_EXIT_GC_UNSAFE;
1269 return rv;
1273 mono_jit_exec_internal (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
1275 MONO_REQ_GC_UNSAFE_MODE;
1276 ERROR_DECL (error);
1277 MonoImage *image = mono_assembly_get_image_internal (assembly);
1279 // We need to ensure that any module cctor for this image
1280 // is run *before* we invoke the entry point
1281 // For more information, see https://blogs.msdn.microsoft.com/junfeng/2005/11/19/module-initializer-a-k-a-module-constructor/
1283 // This is required in order for tools like Costura
1284 // (https://github.com/Fody/Costura) to work properly, as they inject
1285 // a module initializer which sets up event handlers (e.g. AssemblyResolve)
1286 // that allow the main method to run properly
1287 if (!mono_runtime_run_module_cctor(image, domain, error)) {
1288 g_print ("Failed to run module constructor due to %s\n", mono_error_get_message (error));
1289 return 1;
1292 MonoMethod *method;
1293 guint32 entry = mono_image_get_entry_point (image);
1295 if (!entry) {
1296 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
1297 /* FIXME: remove this silly requirement. */
1298 mono_environment_exitcode_set (1);
1299 return 1;
1302 method = mono_get_method_checked (image, entry, NULL, NULL, error);
1303 if (method == NULL){
1304 g_print ("The entry point method could not be loaded due to %s\n", mono_error_get_message (error));
1305 mono_error_cleanup (error);
1306 mono_environment_exitcode_set (1);
1307 return 1;
1310 if (mono_llvm_only) {
1311 MonoObject *exc = NULL;
1312 int res;
1314 res = mono_runtime_try_run_main (method, argc, argv, &exc);
1315 if (exc) {
1316 mono_unhandled_exception_internal (exc);
1317 mono_invoke_unhandled_exception_hook (exc);
1318 g_assert_not_reached ();
1320 return res;
1321 } else {
1322 int res = mono_runtime_run_main_checked (method, argc, argv, error);
1323 if (!is_ok (error)) {
1324 MonoException *ex = mono_error_convert_to_exception (error);
1325 if (ex) {
1326 mono_unhandled_exception_internal (&ex->object);
1327 mono_invoke_unhandled_exception_hook (&ex->object);
1328 g_assert_not_reached ();
1331 return res;
1335 typedef struct
1337 MonoDomain *domain;
1338 const char *file;
1339 int argc;
1340 char **argv;
1341 guint32 opts;
1342 char *aot_options;
1343 } MainThreadArgs;
1345 static void main_thread_handler (gpointer user_data)
1347 MainThreadArgs *main_args = (MainThreadArgs *)user_data;
1348 MonoAssembly *assembly;
1350 if (mono_compile_aot) {
1351 int i, res;
1352 gpointer *aot_state = NULL;
1354 /* Treat the other arguments as assemblies to compile too */
1355 for (i = 0; i < main_args->argc; ++i) {
1356 assembly = mono_domain_assembly_open_internal (main_args->domain, mono_domain_default_alc (main_args->domain), main_args->argv [i]);
1357 if (!assembly) {
1358 if (mono_is_problematic_file (main_args->argv [i])) {
1359 fprintf (stderr, "Info: AOT of problematic assembly %s skipped. This is expected.\n", main_args->argv [i]);
1360 continue;
1361 } else {
1362 fprintf (stderr, "Can not open image %s\n", main_args->argv [i]);
1363 exit (1);
1366 /* Check that the assembly loaded matches the filename */
1368 MonoImageOpenStatus status;
1369 MonoImage *img;
1371 img = mono_image_open (main_args->argv [i], &status);
1372 if (img && strcmp (img->name, assembly->image->name)) {
1373 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);
1374 exit (1);
1377 res = mono_compile_assembly (assembly, main_args->opts, main_args->aot_options, &aot_state);
1378 if (res != 0) {
1379 fprintf (stderr, "AOT of image %s failed.\n", main_args->argv [i]);
1380 exit (1);
1383 if (aot_state) {
1384 res = mono_compile_deferred_assemblies (main_args->opts, main_args->aot_options, &aot_state);
1385 if (res != 0) {
1386 fprintf (stderr, "AOT of mode-specific deferred assemblies failed.\n");
1387 exit (1);
1390 } else {
1391 assembly = mono_domain_assembly_open_internal (main_args->domain, mono_domain_default_alc (main_args->domain), main_args->file);
1392 if (!assembly){
1393 fprintf (stderr, "Can not open image %s\n", main_args->file);
1394 exit (1);
1398 * This must be done in a thread managed by mono since it can invoke
1399 * managed code.
1401 if (main_args->opts & MONO_OPT_PRECOMP)
1402 mono_precompile_assemblies ();
1404 mono_jit_exec (main_args->domain, assembly, main_args->argc, main_args->argv);
1408 static int
1409 load_agent (MonoDomain *domain, char *desc)
1411 ERROR_DECL (error);
1412 char* col = strchr (desc, ':');
1413 char *agent, *args;
1414 MonoAssembly *agent_assembly;
1415 MonoImage *image;
1416 MonoMethod *method;
1417 guint32 entry;
1418 MonoArray *main_args;
1419 gpointer pa [1];
1420 MonoImageOpenStatus open_status;
1422 if (col) {
1423 agent = (char *)g_memdup (desc, col - desc + 1);
1424 agent [col - desc] = '\0';
1425 args = col + 1;
1426 } else {
1427 agent = g_strdup (desc);
1428 args = NULL;
1431 MonoAssemblyOpenRequest req;
1432 mono_assembly_request_prepare (&req.request, sizeof (req), MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_get_root_domain ()));
1433 agent_assembly = mono_assembly_request_open (agent, &req, &open_status);
1434 if (!agent_assembly) {
1435 fprintf (stderr, "Cannot open agent assembly '%s': %s.\n", agent, mono_image_strerror (open_status));
1436 g_free (agent);
1437 return 2;
1441 * Can't use mono_jit_exec (), as it sets things which might confuse the
1442 * real Main method.
1444 image = mono_assembly_get_image_internal (agent_assembly);
1445 entry = mono_image_get_entry_point (image);
1446 if (!entry) {
1447 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
1448 g_free (agent);
1449 return 1;
1452 method = mono_get_method_checked (image, entry, NULL, NULL, error);
1453 if (method == NULL){
1454 g_print ("The entry point method of assembly '%s' could not be loaded due to %s\n", agent, mono_error_get_message (error));
1455 mono_error_cleanup (error);
1456 g_free (agent);
1457 return 1;
1460 mono_thread_set_main (mono_thread_current ());
1462 if (args) {
1463 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 1, error);
1464 if (main_args) {
1465 MonoString *str = mono_string_new_checked (domain, args, error);
1466 if (str)
1467 mono_array_set_internal (main_args, MonoString*, 0, str);
1469 } else {
1470 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 0, error);
1472 if (!main_args) {
1473 g_print ("Could not allocate array for main args of assembly '%s' due to %s\n", agent, mono_error_get_message (error));
1474 mono_error_cleanup (error);
1475 g_free (agent);
1476 return 1;
1480 pa [0] = main_args;
1481 /* Pass NULL as 'exc' so unhandled exceptions abort the runtime */
1482 mono_runtime_invoke_checked (method, NULL, pa, error);
1483 if (!is_ok (error)) {
1484 g_print ("The entry point method of assembly '%s' could not execute due to %s\n", agent, mono_error_get_message (error));
1485 mono_error_cleanup (error);
1486 g_free (agent);
1487 return 1;
1490 g_free (agent);
1491 return 0;
1494 static void
1495 mini_usage_jitdeveloper (void)
1497 int i;
1499 fprintf (stdout,
1500 "Runtime and JIT debugging options:\n"
1501 " --apply-bindings=FILE Apply assembly bindings from FILE (only for AOT)\n"
1502 " --breakonex Inserts a breakpoint on exceptions\n"
1503 " --break METHOD Inserts a breakpoint at METHOD entry\n"
1504 " --break-at-bb METHOD N Inserts a breakpoint in METHOD at BB N\n"
1505 " --compile METHOD Just compile METHOD in assembly\n"
1506 " --compile-all=N Compiles all the methods in the assembly multiple times (default: 1)\n"
1507 " --ncompile N Number of times to compile METHOD (default: 1)\n"
1508 " --print-vtable Print the vtable of all used classes\n"
1509 " --regression Runs the regression test contained in the assembly\n"
1510 " --single-method=OPTS Runs regressions with only one method optimized with OPTS at any time\n"
1511 " --statfile FILE Sets the stat file to FILE\n"
1512 " --stats Print statistics about the JIT operations\n"
1513 " --inject-async-exc METHOD OFFSET Inject an asynchronous exception at METHOD\n"
1514 " --verify-all Run the verifier on all assemblies and methods\n"
1515 " --full-aot Avoid JITting any code\n"
1516 " --llvmonly Use LLVM compiled code only\n"
1517 " --agent=ASSEMBLY[:ARG] Loads the specific agent assembly and executes its Main method with the given argument before loading the main assembly.\n"
1518 " --no-x86-stack-align Don't align stack on x86\n"
1519 "\n"
1520 "The options supported by MONO_DEBUG can also be passed on the command line.\n"
1521 "\n"
1522 "Other options:\n"
1523 " --graph[=TYPE] METHOD Draws a graph of the specified method:\n");
1525 for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
1526 fprintf (stdout, " %-10s %s\n", graph_names [i].name, graph_names [i].desc);
1530 static void
1531 mini_usage_list_opt (void)
1533 int i;
1535 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i)
1536 fprintf (stdout, " %-10s %s\n", optflag_get_name (i), optflag_get_desc (i));
1539 static void
1540 mini_usage (void)
1542 fprintf (stdout,
1543 "Usage is: mono [options] program [program-options]\n"
1544 "\n"
1545 "Development:\n"
1546 " --aot[=<options>] Compiles the assembly to native code\n"
1547 " --debug[=<options>] Enable debugging support, use --help-debug for details\n"
1548 " --debugger-agent=options Enable the debugger agent\n"
1549 " --profile[=profiler] Runs in profiling mode with the specified profiler module\n"
1550 " --trace[=EXPR] Enable tracing, use --help-trace for details\n"
1551 " --jitmap Output a jit method map to /tmp/perf-PID.map\n"
1552 " --help-devel Shows more options available to developers\n"
1553 "\n"
1554 "Runtime:\n"
1555 " --config FILE Loads FILE as the Mono config\n"
1556 " --verbose, -v Increases the verbosity level\n"
1557 " --help, -h Show usage information\n"
1558 " --version, -V Show version information\n"
1559 " --version=number Show version number\n"
1560 " --runtime=VERSION Use the VERSION runtime, instead of autodetecting\n"
1561 " --optimize=OPT Turns on or off a specific optimization\n"
1562 " Use --list-opt to get a list of optimizations\n"
1563 " --attach=OPTIONS Pass OPTIONS to the attach agent in the runtime.\n"
1564 " Currently the only supported option is 'disable'.\n"
1565 " --llvm, --nollvm Controls whenever the runtime uses LLVM to compile code.\n"
1566 " --gc=[sgen,boehm] Select SGen or Boehm GC (runs mono or mono-sgen)\n"
1567 #ifdef TARGET_OSX
1568 " --arch=[32,64] Select architecture (runs mono32 or mono64)\n"
1569 #endif
1570 #ifdef HOST_WIN32
1571 " --mixed-mode Enable mixed-mode image support.\n"
1572 #endif
1573 " --handlers Install custom handlers, use --help-handlers for details.\n"
1574 " --aot-path=PATH List of additional directories to search for AOT images.\n"
1578 static void
1579 mini_trace_usage (void)
1581 fprintf (stdout,
1582 "Tracing options:\n"
1583 " --trace[=EXPR] Trace every call, optional EXPR controls the scope\n"
1584 "\n"
1585 "EXPR is composed of:\n"
1586 " all All assemblies\n"
1587 " none No assemblies\n"
1588 " program Entry point assembly\n"
1589 " assembly Specifies an assembly\n"
1590 " wrapper All wrappers bridging native and managed code\n"
1591 " M:Type:Method Specifies a method\n"
1592 " N:Namespace Specifies a namespace\n"
1593 " T:Type Specifies a type\n"
1594 " E:Type Specifies stack traces for an exception type\n"
1595 " EXPR Includes expression\n"
1596 " -EXPR Excludes expression\n"
1597 " EXPR,EXPR Multiple expressions\n"
1598 " disabled Don't print any output until toggled via SIGUSR2\n");
1601 static void
1602 mini_debug_usage (void)
1604 fprintf (stdout,
1605 "Debugging options:\n"
1606 " --debug[=OPTIONS] Enable debugging support, optional OPTIONS is a comma\n"
1607 " separated list of options\n"
1608 "\n"
1609 "OPTIONS is composed of:\n"
1610 " casts Enable more detailed InvalidCastException messages.\n"
1611 " mdb-optimizations Disable some JIT optimizations which are normally\n"
1612 " disabled when running inside the debugger.\n"
1613 " This is useful if you plan to attach to the running\n"
1614 " process with the debugger.\n");
1617 #if defined(MONO_ARCH_ARCHITECTURE)
1618 /* Redefine MONO_ARCHITECTURE to include more information */
1619 #undef MONO_ARCHITECTURE
1620 #define MONO_ARCHITECTURE MONO_ARCH_ARCHITECTURE
1621 #endif
1623 static char *
1624 mono_get_version_info (void)
1626 GString *output;
1627 output = g_string_new ("");
1629 #ifdef MONO_KEYWORD_THREAD
1630 g_string_append_printf (output, "\tTLS: __thread\n");
1631 #else
1632 g_string_append_printf (output, "\tTLS: \n");
1633 #endif /* MONO_KEYWORD_THREAD */
1635 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
1636 g_string_append_printf (output, "\tSIGSEGV: altstack\n");
1637 #else
1638 g_string_append_printf (output, "\tSIGSEGV: normal\n");
1639 #endif
1641 #ifdef HAVE_EPOLL
1642 g_string_append_printf (output, "\tNotifications: epoll\n");
1643 #elif defined(HAVE_KQUEUE)
1644 g_string_append_printf (output, "\tNotification: kqueue\n");
1645 #else
1646 g_string_append_printf (output, "\tNotification: Thread + polling\n");
1647 #endif
1649 g_string_append_printf (output, "\tArchitecture: %s\n", MONO_ARCHITECTURE);
1650 g_string_append_printf (output, "\tDisabled: %s\n", DISABLED_FEATURES);
1652 g_string_append_printf (output, "\tMisc: ");
1653 #ifdef MONO_SMALL_CONFIG
1654 g_string_append_printf (output, "smallconfig ");
1655 #endif
1657 #ifdef MONO_BIG_ARRAYS
1658 g_string_append_printf (output, "bigarrays ");
1659 #endif
1661 #if !defined(DISABLE_SDB)
1662 g_string_append_printf (output, "softdebug ");
1663 #endif
1664 g_string_append_printf (output, "\n");
1666 #ifndef DISABLE_INTERPRETER
1667 g_string_append_printf (output, "\tInterpreter: yes\n");
1668 #else
1669 g_string_append_printf (output, "\tInterpreter: no\n");
1670 #endif
1672 #ifdef MONO_ARCH_LLVM_SUPPORTED
1673 #ifdef ENABLE_LLVM
1674 g_string_append_printf (output, "\tLLVM: yes(%d)\n", LLVM_API_VERSION);
1675 #else
1676 g_string_append_printf (output, "\tLLVM: supported, not enabled.\n");
1677 #endif
1678 #endif
1680 mono_threads_suspend_policy_init ();
1681 g_string_append_printf (output, "\tSuspend: %s\n", mono_threads_suspend_policy_name (mono_threads_suspend_policy ()));
1683 return g_string_free (output, FALSE);
1686 #ifndef MONO_ARCH_AOT_SUPPORTED
1687 #define error_if_aot_unsupported() do {fprintf (stderr, "AOT compilation is not supported on this platform.\n"); exit (1);} while (0)
1688 #else
1689 #define error_if_aot_unsupported()
1690 #endif
1692 static gboolean enable_debugging;
1695 * mono_jit_parse_options:
1697 * Process the command line options in \p argv as done by the runtime executable.
1698 * This should be called before \c mono_jit_init.
1700 void
1701 mono_jit_parse_options (int argc, char * argv[])
1703 int i;
1704 char *trace_options = NULL;
1705 int mini_verbose_level = 0;
1706 guint32 opt;
1709 * Some options have no effect here, since they influence the behavior of
1710 * mono_main ().
1713 opt = mono_parse_default_optimizations (NULL);
1715 /* FIXME: Avoid code duplication */
1716 for (i = 0; i < argc; ++i) {
1717 if (argv [i] [0] != '-')
1718 break;
1719 if (strncmp (argv [i], "--debugger-agent=", 17) == 0) {
1720 MonoDebugOptions *opt = mini_get_debug_options ();
1722 sdb_options = g_strdup (argv [i] + 17);
1723 opt->mdb_optimizations = TRUE;
1724 enable_debugging = TRUE;
1725 } else if (!strcmp (argv [i], "--soft-breakpoints")) {
1726 MonoDebugOptions *opt = mini_get_debug_options ();
1728 opt->soft_breakpoints = TRUE;
1729 opt->explicit_null_checks = TRUE;
1730 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
1731 opt = parse_optimizations (opt, argv [i] + 11, TRUE);
1732 mono_set_optimizations (opt);
1733 } else if (strncmp (argv [i], "-O=", 3) == 0) {
1734 opt = parse_optimizations (opt, argv [i] + 3, TRUE);
1735 mono_set_optimizations (opt);
1736 } else if (strcmp (argv [i], "--trace") == 0) {
1737 trace_options = (char*)"";
1738 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
1739 trace_options = &argv [i][8];
1740 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
1741 mini_verbose_level++;
1742 } else if (strcmp (argv [i], "--breakonex") == 0) {
1743 MonoDebugOptions *opt = mini_get_debug_options ();
1745 opt->break_on_exc = TRUE;
1746 } else if (strcmp (argv [i], "--stats") == 0) {
1747 mono_counters_enable (-1);
1748 mono_atomic_store_bool (&mono_stats.enabled, TRUE);
1749 mono_atomic_store_bool (&mono_jit_stats.enabled, TRUE);
1750 } else if (strcmp (argv [i], "--break") == 0) {
1751 if (i+1 >= argc){
1752 fprintf (stderr, "Missing method name in --break command line option\n");
1753 exit (1);
1756 if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
1757 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
1758 } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
1759 mono_gc_params_set (argv[i] + 12);
1760 } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
1761 mono_gc_debug_set (argv[i] + 11);
1762 } else if (strcmp (argv [i], "--llvm") == 0) {
1763 #ifndef MONO_ARCH_LLVM_SUPPORTED
1764 fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
1765 #elif !defined(ENABLE_LLVM)
1766 fprintf (stderr, "Mono Warning: --llvm not enabled in this runtime.\n");
1767 #else
1768 mono_use_llvm = TRUE;
1769 #endif
1770 } else if (argv [i][0] == '-' && argv [i][1] == '-' && mini_parse_debug_option (argv [i] + 2)) {
1771 } else {
1772 fprintf (stderr, "Unsupported command line option: '%s'\n", argv [i]);
1773 exit (1);
1777 if (trace_options != NULL) {
1779 * Need to call this before mini_init () so we can trace methods
1780 * compiled there too.
1782 mono_jit_trace_calls = mono_trace_set_options (trace_options);
1783 if (mono_jit_trace_calls == NULL)
1784 exit (1);
1787 if (mini_verbose_level)
1788 mono_set_verbose_level (mini_verbose_level);
1791 static void
1792 mono_set_use_smp (int use_smp)
1794 #if HAVE_SCHED_SETAFFINITY
1795 if (!use_smp) {
1796 unsigned long proc_mask = 1;
1797 #ifdef GLIBC_BEFORE_2_3_4_SCHED_SETAFFINITY
1798 sched_setaffinity (getpid(), (gpointer)&proc_mask);
1799 #else
1800 sched_setaffinity (getpid(), sizeof (unsigned long), (const cpu_set_t *)&proc_mask);
1801 #endif
1803 #endif
1806 static void
1807 switch_gc (char* argv[], const char* target_gc)
1809 GString *path;
1811 if (!strcmp (mono_gc_get_gc_name (), target_gc)) {
1812 return;
1815 path = g_string_new (argv [0]);
1817 /*Running mono without any argument*/
1818 if (strstr (argv [0], "-sgen"))
1819 g_string_truncate (path, path->len - 5);
1820 else if (strstr (argv [0], "-boehm"))
1821 g_string_truncate (path, path->len - 6);
1823 g_string_append_c (path, '-');
1824 g_string_append (path, target_gc);
1826 #ifdef HAVE_EXECVP
1827 execvp (path->str, argv);
1828 fprintf (stderr, "Error: Failed to switch to %s gc. mono-%s is not installed.\n", target_gc, target_gc);
1829 #else
1830 fprintf (stderr, "Error: --gc=<NAME> option not supported on this platform.\n");
1831 #endif
1834 #ifdef TARGET_OSX
1837 * tries to increase the minimum number of files, if the number is below 1024
1839 static void
1840 darwin_change_default_file_handles ()
1842 struct rlimit limit;
1844 if (getrlimit (RLIMIT_NOFILE, &limit) == 0){
1845 if (limit.rlim_cur < 1024){
1846 limit.rlim_cur = MAX(1024,limit.rlim_cur);
1847 setrlimit (RLIMIT_NOFILE, &limit);
1852 static void
1853 switch_arch (char* argv[], const char* target_arch)
1855 GString *path;
1856 gsize arch_offset;
1858 if ((strcmp (target_arch, "32") == 0 && strcmp (MONO_ARCHITECTURE, "x86") == 0) ||
1859 (strcmp (target_arch, "64") == 0 && strcmp (MONO_ARCHITECTURE, "amd64") == 0)) {
1860 return; /* matching arch loaded */
1863 path = g_string_new (argv [0]);
1864 arch_offset = path->len -2; /* last two characters */
1866 /* Remove arch suffix if present */
1867 if (strstr (&path->str[arch_offset], "32") || strstr (&path->str[arch_offset], "64")) {
1868 g_string_truncate (path, arch_offset);
1871 g_string_append (path, target_arch);
1873 if (execvp (path->str, argv) < 0) {
1874 fprintf (stderr, "Error: --arch=%s Failed to switch to '%s'.\n", target_arch, path->str);
1875 exit (1);
1879 #endif
1881 #define MONO_HANDLERS_ARGUMENT "--handlers="
1882 #define MONO_HANDLERS_ARGUMENT_LEN G_N_ELEMENTS(MONO_HANDLERS_ARGUMENT)-1
1884 static void
1885 apply_root_domain_configuration_file_bindings (MonoDomain *domain, char *root_domain_configuration_file)
1887 g_assert (domain->setup == NULL || domain->setup->configuration_file == NULL);
1888 g_assert (!domain->assembly_bindings_parsed);
1890 mono_domain_parse_assembly_bindings (domain, 0, 0, root_domain_configuration_file);
1894 static void
1895 mono_check_interp_supported (void)
1897 #ifdef DISABLE_INTERPRETER
1898 g_error ("Mono IL interpreter support is missing\n");
1899 #endif
1901 #ifdef MONO_CROSS_COMPILE
1902 g_error ("--interpreter on cross-compile runtimes not supported\n");
1903 #endif
1905 #ifndef MONO_ARCH_INTERPRETER_SUPPORTED
1906 g_error ("--interpreter not supported on this architecture.\n");
1907 #endif
1910 static int
1911 mono_exec_regression_internal (int verbose_level, int count, char *images [], gboolean single_method)
1913 mono_do_single_method_regression = single_method;
1914 if (mono_use_interpreter) {
1915 if (mono_interp_regression_list (verbose_level, count, images)) {
1916 g_print ("Regression ERRORS!\n");
1917 return 1;
1919 return 0;
1921 if (mini_regression_list (verbose_level, count, images)) {
1922 g_print ("Regression ERRORS!\n");
1923 return 1;
1925 return 0;
1930 * Returns TRUE for success, FALSE for failure.
1932 gboolean
1933 mono_regression_test_step (int verbose_level, const char *image, const char *method_name)
1935 if (method_name) {
1936 //TODO
1937 } else {
1938 do_regression_retries = TRUE;
1941 char *images[] = {
1942 (char*)image,
1943 NULL
1946 return mono_exec_regression_internal (verbose_level, 1, images, FALSE) == 0;
1949 #ifdef ENABLE_ICALL_SYMBOL_MAP
1950 /* Print the icall table as JSON */
1951 static void
1952 print_icall_table (void)
1954 // We emit some dummy values to make the code simpler
1956 printf ("[\n{ \"klass\": \"\", \"icalls\": [");
1957 #define NOHANDLES(inner) inner
1958 #define HANDLES(id, name, func, ...) printf ("\t,{ \"name\": \"%s\", \"func\": \"%s_raw\", \"handles\": true }\n", name, #func);
1959 #define HANDLES_REUSE_WRAPPER HANDLES
1960 #define MONO_HANDLE_REGISTER_ICALL(...) /* nothing */
1961 #define ICALL_TYPE(id,name,first) printf ("]},\n { \"klass\":\"%s\", \"icalls\": [{} ", name);
1962 #define ICALL(id,name,func) printf ("\t,{ \"name\": \"%s\", \"func\": \"%s\", \"handles\": false }\n", name, #func);
1963 #include <mono/metadata/icall-def.h>
1965 printf ("]}\n]\n");
1967 #endif
1970 * mono_main:
1971 * \param argc number of arguments in the argv array
1972 * \param argv array of strings containing the startup arguments
1973 * Launches the Mono JIT engine and parses all the command line options
1974 * in the same way that the mono command line VM would.
1977 mono_main (int argc, char* argv[])
1979 MainThreadArgs main_args;
1980 MonoAssembly *assembly;
1981 MonoMethodDesc *desc;
1982 MonoMethod *method;
1983 MonoCompile *cfg;
1984 MonoDomain *domain;
1985 MonoImageOpenStatus open_status;
1986 const char* aname, *mname = NULL;
1987 char *config_file = NULL;
1988 int i, count = 1;
1989 guint32 opt, action = DO_EXEC, recompilation_times = 1;
1990 MonoGraphOptions mono_graph_options = (MonoGraphOptions)0;
1991 int mini_verbose_level = 0;
1992 char *trace_options = NULL;
1993 char *aot_options = NULL;
1994 char *forced_version = NULL;
1995 GPtrArray *agents = NULL;
1996 char *attach_options = NULL;
1997 char *extra_bindings_config_file = NULL;
1998 #ifdef MONO_JIT_INFO_TABLE_TEST
1999 int test_jit_info_table = FALSE;
2000 #endif
2001 #ifdef HOST_WIN32
2002 int mixed_mode = FALSE;
2003 #endif
2005 #ifdef MOONLIGHT
2006 #ifndef HOST_WIN32
2007 /* stdout defaults to block buffering if it's not writing to a terminal, which
2008 * happens with our test harness: we redirect stdout to capture it. Force line
2009 * buffering in all cases. */
2010 setlinebuf (stdout);
2011 #endif
2012 #endif
2014 setlocale (LC_ALL, "");
2016 #if TARGET_OSX
2017 darwin_change_default_file_handles ();
2018 #endif
2020 if (g_hasenv ("MONO_NO_SMP"))
2021 mono_set_use_smp (FALSE);
2023 #ifdef MONO_JEMALLOC_ENABLED
2025 gboolean use_jemalloc = FALSE;
2026 #ifdef MONO_JEMALLOC_DEFAULT
2027 use_jemalloc = TRUE;
2028 #endif
2029 if (!use_jemalloc)
2030 use_jemalloc = g_hasenv ("MONO_USE_JEMALLOC");
2032 if (use_jemalloc)
2033 mono_init_jemalloc ();
2035 #endif
2037 g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
2038 g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
2040 opt = mono_parse_default_optimizations (NULL);
2042 for (i = 1; i < argc; ++i) {
2043 if (argv [i] [0] != '-')
2044 break;
2045 if (strcmp (argv [i], "--regression") == 0) {
2046 action = DO_REGRESSION;
2047 } else if (strncmp (argv [i], "--single-method=", 16) == 0) {
2048 char *full_opts = g_strdup_printf ("-all,%s", argv [i] + 16);
2049 action = DO_SINGLE_METHOD_REGRESSION;
2050 mono_single_method_regression_opt = parse_optimizations (opt, full_opts, TRUE);
2051 g_free (full_opts);
2052 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
2053 mini_verbose_level++;
2054 } else if (strcmp (argv [i], "--version=number") == 0) {
2055 g_print ("%s\n", VERSION);
2056 return 0;
2057 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
2058 char *build = mono_get_runtime_build_info ();
2059 char *gc_descr;
2061 g_print ("Mono JIT compiler version %s\nCopyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com\n", build);
2062 g_free (build);
2063 char *info = mono_get_version_info ();
2064 g_print (info);
2065 g_free (info);
2067 gc_descr = mono_gc_get_description ();
2068 g_print ("\tGC: %s\n", gc_descr);
2069 g_free (gc_descr);
2070 return 0;
2071 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
2072 mini_usage ();
2073 return 0;
2074 } else if (strcmp (argv [i], "--help-trace") == 0){
2075 mini_trace_usage ();
2076 return 0;
2077 } else if (strcmp (argv [i], "--help-devel") == 0){
2078 mini_usage_jitdeveloper ();
2079 return 0;
2080 } else if (strcmp (argv [i], "--help-debug") == 0){
2081 mini_debug_usage ();
2082 return 0;
2083 } else if (strcmp (argv [i], "--list-opt") == 0){
2084 mini_usage_list_opt ();
2085 return 0;
2086 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
2087 if (i + 1 >= argc){
2088 fprintf (stderr, "error: --statfile requires a filename argument\n");
2089 return 1;
2091 mini_stats_fd = fopen (argv [++i], "w+");
2092 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
2093 opt = parse_optimizations (opt, argv [i] + 11, TRUE);
2094 } else if (strncmp (argv [i], "-O=", 3) == 0) {
2095 opt = parse_optimizations (opt, argv [i] + 3, TRUE);
2096 } else if (strncmp (argv [i], "--bisect=", 9) == 0) {
2097 char *param = argv [i] + 9;
2098 char *sep = strchr (param, ':');
2099 if (!sep) {
2100 fprintf (stderr, "Error: --bisect requires OPT:FILENAME\n");
2101 return 1;
2103 char *opt_string = g_strndup (param, sep - param);
2104 guint32 opt = parse_optimizations (0, opt_string, FALSE);
2105 g_free (opt_string);
2106 mono_set_bisect_methods (opt, sep + 1);
2107 } else if (strcmp (argv [i], "--gc=sgen") == 0) {
2108 switch_gc (argv, "sgen");
2109 } else if (strcmp (argv [i], "--gc=boehm") == 0) {
2110 switch_gc (argv, "boehm");
2111 } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
2112 mono_gc_params_set (argv[i] + 12);
2113 } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
2114 mono_gc_debug_set (argv[i] + 11);
2116 #ifdef TARGET_OSX
2117 else if (strcmp (argv [i], "--arch=32") == 0) {
2118 switch_arch (argv, "32");
2119 } else if (strcmp (argv [i], "--arch=64") == 0) {
2120 switch_arch (argv, "64");
2122 #endif
2123 else if (strcmp (argv [i], "--config") == 0) {
2124 if (i +1 >= argc){
2125 fprintf (stderr, "error: --config requires a filename argument\n");
2126 return 1;
2128 config_file = argv [++i];
2129 #ifdef HOST_WIN32
2130 } else if (strcmp (argv [i], "--mixed-mode") == 0) {
2131 mixed_mode = TRUE;
2132 #endif
2133 } else if (strcmp (argv [i], "--ncompile") == 0) {
2134 if (i + 1 >= argc){
2135 fprintf (stderr, "error: --ncompile requires an argument\n");
2136 return 1;
2138 count = atoi (argv [++i]);
2139 action = DO_BENCH;
2140 } else if (strcmp (argv [i], "--trace") == 0) {
2141 trace_options = (char*)"";
2142 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
2143 trace_options = &argv [i][8];
2144 } else if (strcmp (argv [i], "--breakonex") == 0) {
2145 MonoDebugOptions *opt = mini_get_debug_options ();
2147 opt->break_on_exc = TRUE;
2148 } else if (strcmp (argv [i], "--break") == 0) {
2149 if (i+1 >= argc){
2150 fprintf (stderr, "Missing method name in --break command line option\n");
2151 return 1;
2154 if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
2155 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
2156 } else if (strcmp (argv [i], "--break-at-bb") == 0) {
2157 if (i + 2 >= argc) {
2158 fprintf (stderr, "Missing method name or bb num in --break-at-bb command line option.");
2159 return 1;
2161 mono_break_at_bb_method = mono_method_desc_new (argv [++i], TRUE);
2162 if (mono_break_at_bb_method == NULL) {
2163 fprintf (stderr, "Method name is in a bad format in --break-at-bb command line option.");
2164 return 1;
2166 mono_break_at_bb_bb_num = atoi (argv [++i]);
2167 } else if (strcmp (argv [i], "--inject-async-exc") == 0) {
2168 if (i + 2 >= argc) {
2169 fprintf (stderr, "Missing method name or position in --inject-async-exc command line option\n");
2170 return 1;
2172 mono_inject_async_exc_method = mono_method_desc_new (argv [++i], TRUE);
2173 if (mono_inject_async_exc_method == NULL) {
2174 fprintf (stderr, "Method name is in a bad format in --inject-async-exc command line option\n");
2175 return 1;
2177 mono_inject_async_exc_pos = atoi (argv [++i]);
2178 } else if (strcmp (argv [i], "--verify-all") == 0) {
2179 mono_verifier_enable_verify_all ();
2180 } else if (strcmp (argv [i], "--full-aot") == 0) {
2181 mono_jit_set_aot_mode (MONO_AOT_MODE_FULL);
2182 } else if (strcmp (argv [i], "--llvmonly") == 0) {
2183 mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY);
2184 } else if (strcmp (argv [i], "--hybrid-aot") == 0) {
2185 mono_jit_set_aot_mode (MONO_AOT_MODE_HYBRID);
2186 } else if (strcmp (argv [i], "--full-aot-interp") == 0) {
2187 mono_jit_set_aot_mode (MONO_AOT_MODE_INTERP);
2188 } else if (strcmp (argv [i], "--llvmonly-interp") == 0) {
2189 mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY_INTERP);
2190 } else if (strcmp (argv [i], "--print-vtable") == 0) {
2191 mono_print_vtable = TRUE;
2192 } else if (strcmp (argv [i], "--stats") == 0) {
2193 mono_counters_enable (-1);
2194 mono_atomic_store_bool (&mono_stats.enabled, TRUE);
2195 mono_atomic_store_bool (&mono_jit_stats.enabled, TRUE);
2196 #ifndef DISABLE_AOT
2197 } else if (strcmp (argv [i], "--aot") == 0) {
2198 error_if_aot_unsupported ();
2199 mono_compile_aot = TRUE;
2200 } else if (strncmp (argv [i], "--aot=", 6) == 0) {
2201 error_if_aot_unsupported ();
2202 mono_compile_aot = TRUE;
2203 if (aot_options) {
2204 char *tmp = g_strdup_printf ("%s,%s", aot_options, &argv [i][6]);
2205 g_free (aot_options);
2206 aot_options = tmp;
2207 } else {
2208 aot_options = g_strdup (&argv [i][6]);
2210 #endif
2211 } else if (strncmp (argv [i], "--apply-bindings=", 17) == 0) {
2212 extra_bindings_config_file = &argv[i][17];
2213 } else if (strncmp (argv [i], "--aot-path=", 11) == 0) {
2214 char **splitted;
2216 splitted = g_strsplit (argv [i] + 11, G_SEARCHPATH_SEPARATOR_S, 1000);
2217 while (*splitted) {
2218 char *tmp = *splitted;
2219 mono_aot_paths = g_list_append (mono_aot_paths, g_strdup (tmp));
2220 g_free (tmp);
2221 splitted++;
2223 } else if (strncmp (argv [i], "--compile-all=", 14) == 0) {
2224 action = DO_COMPILE;
2225 recompilation_times = atoi (argv [i] + 14);
2226 } else if (strcmp (argv [i], "--compile-all") == 0) {
2227 action = DO_COMPILE;
2228 } else if (strncmp (argv [i], "--runtime=", 10) == 0) {
2229 forced_version = &argv [i][10];
2230 } else if (strcmp (argv [i], "--jitmap") == 0) {
2231 mono_enable_jit_map ();
2232 } else if (strcmp (argv [i], "--profile") == 0) {
2233 mini_add_profiler_argument (NULL);
2234 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
2235 mini_add_profiler_argument (argv [i] + 10);
2236 } else if (strncmp (argv [i], "--agent=", 8) == 0) {
2237 if (agents == NULL)
2238 agents = g_ptr_array_new ();
2239 g_ptr_array_add (agents, argv [i] + 8);
2240 } else if (strncmp (argv [i], "--attach=", 9) == 0) {
2241 attach_options = argv [i] + 9;
2242 } else if (strcmp (argv [i], "--compile") == 0) {
2243 if (i + 1 >= argc){
2244 fprintf (stderr, "error: --compile option requires a method name argument\n");
2245 return 1;
2248 mname = argv [++i];
2249 action = DO_BENCH;
2250 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
2251 if (i + 1 >= argc){
2252 fprintf (stderr, "error: --graph option requires a method name argument\n");
2253 return 1;
2256 mono_graph_options = mono_parse_graph_options (argv [i] + 8);
2257 mname = argv [++i];
2258 action = DO_DRAW;
2259 } else if (strcmp (argv [i], "--graph") == 0) {
2260 if (i + 1 >= argc){
2261 fprintf (stderr, "error: --graph option requires a method name argument\n");
2262 return 1;
2265 mname = argv [++i];
2266 mono_graph_options = MONO_GRAPH_CFG;
2267 action = DO_DRAW;
2268 } else if (strcmp (argv [i], "--debug") == 0) {
2269 enable_debugging = TRUE;
2270 } else if (strncmp (argv [i], "--debug=", 8) == 0) {
2271 enable_debugging = TRUE;
2272 if (!parse_debug_options (argv [i] + 8))
2273 return 1;
2274 } else if (strncmp (argv [i], "--debugger-agent=", 17) == 0) {
2275 MonoDebugOptions *opt = mini_get_debug_options ();
2277 sdb_options = g_strdup (argv [i] + 17);
2278 opt->mdb_optimizations = TRUE;
2279 enable_debugging = TRUE;
2280 } else if (strcmp (argv [i], "--security") == 0) {
2281 #ifndef DISABLE_SECURITY
2282 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2283 #else
2284 fprintf (stderr, "error: --security: not compiled with security manager support");
2285 return 1;
2286 #endif
2287 } else if (strncmp (argv [i], "--security=", 11) == 0) {
2288 /* Note: validil, and verifiable need to be
2289 accepted even if DISABLE_SECURITY is defined. */
2291 if (strcmp (argv [i] + 11, "core-clr") == 0) {
2292 #ifndef DISABLE_SECURITY
2293 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2294 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
2295 #else
2296 fprintf (stderr, "error: --security: not compiled with CoreCLR support");
2297 return 1;
2298 #endif
2299 } else if (strcmp (argv [i] + 11, "core-clr-test") == 0) {
2300 #ifndef DISABLE_SECURITY
2301 /* fixme should we enable verifiable code here?*/
2302 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
2303 mono_security_core_clr_test = TRUE;
2304 #else
2305 fprintf (stderr, "error: --security: not compiled with CoreCLR support");
2306 return 1;
2307 #endif
2308 } else if (strcmp (argv [i] + 11, "cas") == 0) {
2309 #ifndef DISABLE_SECURITY
2310 fprintf (stderr, "warning: --security=cas not supported.");
2311 #else
2312 fprintf (stderr, "error: --security: not compiled with CAS support");
2313 return 1;
2314 #endif
2315 } else if (strcmp (argv [i] + 11, "validil") == 0) {
2316 mono_verifier_set_mode (MONO_VERIFIER_MODE_VALID);
2317 } else if (strcmp (argv [i] + 11, "verifiable") == 0) {
2318 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2319 } else {
2320 fprintf (stderr, "error: --security= option has invalid argument (cas, core-clr, verifiable or validil)\n");
2321 return 1;
2323 } else if (strcmp (argv [i], "--desktop") == 0) {
2324 mono_gc_set_desktop_mode ();
2325 /* Put more desktop-specific optimizations here */
2326 } else if (strcmp (argv [i], "--server") == 0){
2327 mono_config_set_server_mode (TRUE);
2328 /* Put more server-specific optimizations here */
2329 } else if (strcmp (argv [i], "--inside-mdb") == 0) {
2330 action = DO_DEBUGGER;
2331 } else if (strncmp (argv [i], "--wapi=", 7) == 0) {
2332 fprintf (stderr, "--wapi= option no longer supported\n.");
2333 return 1;
2334 } else if (strcmp (argv [i], "--no-x86-stack-align") == 0) {
2335 mono_do_x86_stack_align = FALSE;
2336 #ifdef MONO_JIT_INFO_TABLE_TEST
2337 } else if (strcmp (argv [i], "--test-jit-info-table") == 0) {
2338 test_jit_info_table = TRUE;
2339 #endif
2340 } else if (strcmp (argv [i], "--llvm") == 0) {
2341 #ifndef MONO_ARCH_LLVM_SUPPORTED
2342 fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
2343 #elif !defined(ENABLE_LLVM)
2344 fprintf (stderr, "Mono Warning: --llvm not enabled in this runtime.\n");
2345 #else
2346 mono_use_llvm = TRUE;
2347 #endif
2348 } else if (strcmp (argv [i], "--nollvm") == 0){
2349 mono_use_llvm = FALSE;
2350 } else if ((strcmp (argv [i], "--interpreter") == 0) || !strcmp (argv [i], "--interp")) {
2351 mono_runtime_set_execution_mode (MONO_EE_MODE_INTERP);
2352 } else if (strncmp (argv [i], "--interp=", 9) == 0) {
2353 mono_runtime_set_execution_mode_full (MONO_EE_MODE_INTERP, FALSE);
2354 mono_interp_opts_string = argv [i] + 9;
2355 } else if (strcmp (argv [i], "--print-icall-table") == 0) {
2356 #ifdef ENABLE_ICALL_SYMBOL_MAP
2357 print_icall_table ();
2358 exit (0);
2359 #else
2360 fprintf (stderr, "--print-icall-table requires a runtime configured with the --enable-icall-symbol-map option.\n");
2361 exit (1);
2362 #endif
2363 } else if (strncmp (argv [i], "--assembly-loader=", strlen("--assembly-loader=")) == 0) {
2364 gchar *arg = argv [i] + strlen ("--assembly-loader=");
2365 if (strcmp (arg, "strict") == 0)
2366 mono_loader_set_strict_strong_names (TRUE);
2367 else if (strcmp (arg, "legacy") == 0)
2368 mono_loader_set_strict_strong_names (FALSE);
2369 else
2370 fprintf (stderr, "Warning: unknown argument to --assembly-loader. Should be \"strict\" or \"legacy\"\n");
2371 } else if (strncmp (argv [i], MONO_HANDLERS_ARGUMENT, MONO_HANDLERS_ARGUMENT_LEN) == 0) {
2372 //Install specific custom handlers.
2373 if (!mono_runtime_install_custom_handlers (argv[i] + MONO_HANDLERS_ARGUMENT_LEN)) {
2374 fprintf (stderr, "error: " MONO_HANDLERS_ARGUMENT ", one or more unknown handlers: '%s'\n", argv [i]);
2375 return 1;
2377 } else if (strcmp (argv [i], "--help-handlers") == 0) {
2378 mono_runtime_install_custom_handlers_usage ();
2379 return 0;
2380 } else if (strncmp (argv [i], "--response=", 11) == 0){
2381 gchar *response_content;
2382 gchar *response_options;
2383 gsize response_content_len;
2385 if (!g_file_get_contents (&argv[i][11], &response_content, &response_content_len, NULL)){
2386 fprintf (stderr, "The specified response file can not be read\n");
2387 exit (1);
2390 response_options = response_content;
2392 // Check for UTF8 BOM in file and remove if found.
2393 if (response_content_len >= 3 && response_content [0] == '\xef' && response_content [1] == '\xbb' && response_content [2] == '\xbf') {
2394 response_content_len -= 3;
2395 response_options += 3;
2398 if (response_content_len == 0) {
2399 fprintf (stderr, "The specified response file is empty\n");
2400 exit (1);
2403 mono_parse_response_options (response_options, &argc, &argv, FALSE);
2404 g_free (response_content);
2405 } else if (argv [i][0] == '-' && argv [i][1] == '-' && mini_parse_debug_option (argv [i] + 2)) {
2406 } else if (strcmp (argv [i], "--use-map-jit") == 0){
2407 mono_setmmapjit (TRUE);
2408 } else {
2409 fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
2410 return 1;
2414 #if defined(DISABLE_HW_TRAPS) || defined(MONO_ARCH_DISABLE_HW_TRAPS)
2415 // Signal handlers not available
2417 MonoDebugOptions *opt = mini_get_debug_options ();
2418 opt->explicit_null_checks = TRUE;
2420 #endif
2422 if (!argv [i]) {
2423 mini_usage ();
2424 return 1;
2428 * XXX: verify if other OSes need it; many platforms seem to have it so that
2429 * mono_w32process_get_path -> mono_w32process_get_name, and the name is not
2430 * necessarily a path instead of just the program name
2432 #if defined (_AIX)
2434 * mono_w32process_get_path on these can only return a name, not a path;
2435 * which may not be good for us if the mono command name isn't on $PATH,
2436 * like in CI scenarios. chances are argv based is fine if we inherited
2437 * the environment variables.
2439 mono_w32process_set_cli_launcher (argv [0]);
2440 #elif !defined(HOST_WIN32) && defined(HAVE_UNISTD_H)
2442 * If we are not embedded, use the mono runtime executable to run managed exe's.
2445 char *runtime_path;
2447 runtime_path = mono_w32process_get_path (getpid ());
2448 if (runtime_path) {
2449 mono_w32process_set_cli_launcher (runtime_path);
2450 g_free (runtime_path);
2453 #endif
2455 if (g_hasenv ("MONO_XDEBUG"))
2456 enable_debugging = TRUE;
2458 #ifdef MONO_CROSS_COMPILE
2459 if (!mono_compile_aot) {
2460 fprintf (stderr, "This mono runtime is compiled for cross-compiling. Only the --aot option is supported.\n");
2461 exit (1);
2463 #if TARGET_SIZEOF_VOID_P == 4 && (defined(TARGET_ARM64) || defined(TARGET_AMD64)) && !defined(MONO_ARCH_ILP32)
2464 fprintf (stderr, "Can't cross-compile on 32-bit platforms to 64-bit architecture.\n");
2465 exit (1);
2466 #endif
2467 #endif
2469 if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
2470 g_set_prgname (argv[i]);
2473 mono_counters_init ();
2475 #ifndef HOST_WIN32
2476 mono_w32handle_init ();
2477 #endif
2479 /* Set rootdir before loading config */
2480 mono_set_rootdir ();
2482 mono_attach_parse_options (attach_options);
2484 if (trace_options != NULL){
2486 * Need to call this before mini_init () so we can trace methods
2487 * compiled there too.
2489 mono_jit_trace_calls = mono_trace_set_options (trace_options);
2490 if (mono_jit_trace_calls == NULL)
2491 exit (1);
2494 #ifdef DISABLE_JIT
2495 if (!mono_aot_only && !mono_use_interpreter) {
2496 fprintf (stderr, "This runtime has been configured with --enable-minimal=jit, so the --full-aot command line option is required.\n");
2497 exit (1);
2499 #endif
2501 if (action == DO_DEBUGGER) {
2502 enable_debugging = TRUE;
2503 g_print ("The Mono Debugger is no longer supported.\n");
2504 return 1;
2505 } else if (enable_debugging)
2506 mono_debug_init (MONO_DEBUG_FORMAT_MONO);
2508 #ifdef HOST_WIN32
2509 if (mixed_mode)
2510 mono_load_coree (argv [i]);
2511 #endif
2513 /* Parse gac loading options before loading assemblies. */
2514 if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER || action == DO_REGRESSION) {
2515 mono_config_parse (config_file);
2518 mono_set_defaults (mini_verbose_level, opt);
2519 domain = mini_init (argv [i], forced_version);
2521 mono_gc_set_stack_end (&domain);
2523 if (agents) {
2524 int i;
2526 for (i = 0; i < agents->len; ++i) {
2527 int res = load_agent (domain, (char*)g_ptr_array_index (agents, i));
2528 if (res) {
2529 g_ptr_array_free (agents, TRUE);
2530 mini_cleanup (domain);
2531 return 1;
2535 g_ptr_array_free (agents, TRUE);
2538 switch (action) {
2539 case DO_SINGLE_METHOD_REGRESSION:
2540 case DO_REGRESSION:
2541 return mono_exec_regression_internal (mini_verbose_level, argc -i, argv + i, action == DO_SINGLE_METHOD_REGRESSION);
2543 case DO_BENCH:
2544 if (argc - i != 1 || mname == NULL) {
2545 g_print ("Usage: mini --ncompile num --compile method assembly\n");
2546 mini_cleanup (domain);
2547 return 1;
2549 aname = argv [i];
2550 break;
2551 case DO_COMPILE:
2552 if (argc - i != 1) {
2553 mini_usage ();
2554 mini_cleanup (domain);
2555 return 1;
2557 aname = argv [i];
2558 break;
2559 case DO_DRAW:
2560 if (argc - i != 1 || mname == NULL) {
2561 mini_usage ();
2562 mini_cleanup (domain);
2563 return 1;
2565 aname = argv [i];
2566 break;
2567 default:
2568 if (argc - i < 1) {
2569 mini_usage ();
2570 mini_cleanup (domain);
2571 return 1;
2573 aname = argv [i];
2574 break;
2577 #ifdef MONO_JIT_INFO_TABLE_TEST
2578 if (test_jit_info_table)
2579 jit_info_table_test (domain);
2580 #endif
2582 if (mono_compile_aot && extra_bindings_config_file != NULL) {
2583 apply_root_domain_configuration_file_bindings (domain, extra_bindings_config_file);
2586 MonoAssemblyOpenRequest open_req;
2587 mono_assembly_request_prepare (&open_req.request, sizeof (open_req), MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_get_root_domain ()));
2588 assembly = mono_assembly_request_open (aname, &open_req, &open_status);
2589 if (!assembly && !mono_compile_aot) {
2590 fprintf (stderr, "Cannot open assembly '%s': %s.\n", aname, mono_image_strerror (open_status));
2591 mini_cleanup (domain);
2592 return 2;
2595 mono_callspec_set_assembly (assembly);
2597 if (mono_compile_aot || action == DO_EXEC) {
2598 const char *error;
2600 //mono_set_rootdir ();
2602 error = mono_check_corlib_version ();
2603 if (error) {
2604 fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
2605 fprintf (stderr, "Loaded from: %s\n",
2606 mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown");
2607 fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.mono-project.com/download.\n");
2608 exit (1);
2611 #if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
2612 /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
2613 if (!enable_debugging && !mono_compile_aot && mono_assembly_get_image_internal (assembly)->image_info->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
2614 FreeConsole ();
2615 #endif
2617 main_args.domain = domain;
2618 main_args.file = aname;
2619 main_args.argc = argc - i;
2620 main_args.argv = argv + i;
2621 main_args.opts = opt;
2622 main_args.aot_options = aot_options;
2623 main_thread_handler (&main_args);
2624 mono_thread_manage ();
2626 mini_cleanup (domain);
2628 /* Look up return value from System.Environment.ExitCode */
2629 i = mono_environment_exitcode_get ();
2630 return i;
2631 } else if (action == DO_COMPILE) {
2632 compile_all_methods (assembly, mini_verbose_level, opt, recompilation_times);
2633 mini_cleanup (domain);
2634 return 0;
2635 } else if (action == DO_DEBUGGER) {
2636 return 1;
2638 desc = mono_method_desc_new (mname, 0);
2639 if (!desc) {
2640 g_print ("Invalid method name %s\n", mname);
2641 mini_cleanup (domain);
2642 return 3;
2644 method = mono_method_desc_search_in_image (desc, mono_assembly_get_image_internal (assembly));
2645 if (!method) {
2646 g_print ("Cannot find method %s\n", mname);
2647 mini_cleanup (domain);
2648 return 3;
2651 #ifndef DISABLE_JIT
2652 if (action == DO_DRAW) {
2653 int part = 0;
2655 switch (mono_graph_options) {
2656 case MONO_GRAPH_DTREE:
2657 part = 1;
2658 opt |= MONO_OPT_LOOP;
2659 break;
2660 case MONO_GRAPH_CFG_CODE:
2661 part = 1;
2662 break;
2663 case MONO_GRAPH_CFG_SSA:
2664 part = 2;
2665 break;
2666 case MONO_GRAPH_CFG_OPTCODE:
2667 part = 3;
2668 break;
2669 default:
2670 break;
2673 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2674 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
2675 MonoMethod *nm;
2676 nm = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
2677 cfg = mini_method_compile (nm, opt, mono_get_root_domain (), (JitFlags)0, part, -1);
2679 else
2680 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, part, -1);
2681 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
2682 g_warning ("no SSA info available (use -O=deadce)");
2683 return 1;
2685 mono_draw_graph (cfg, mono_graph_options);
2686 mono_destroy_compile (cfg);
2688 } else if (action == DO_BENCH) {
2689 if (mini_stats_fd) {
2690 const char *n;
2691 double no_opt_time = 0.0;
2692 GTimer *timer = g_timer_new ();
2693 fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n",
2694 mono_method_full_name (method, TRUE));
2695 fprintf (mini_stats_fd, "@data = (\n");
2696 fprintf (mini_stats_fd, "[");
2697 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
2698 opt = opt_sets [i];
2699 n = mono_opt_descr (opt);
2700 if (!n [0])
2701 n = "none";
2702 fprintf (mini_stats_fd, "\"%s\",", n);
2704 fprintf (mini_stats_fd, "],\n[");
2706 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
2707 int j;
2708 double elapsed;
2709 opt = opt_sets [i];
2710 g_timer_start (timer);
2711 for (j = 0; j < count; ++j) {
2712 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2713 mono_destroy_compile (cfg);
2715 g_timer_stop (timer);
2716 elapsed = g_timer_elapsed (timer, NULL);
2717 if (!opt)
2718 no_opt_time = elapsed;
2719 fprintf (mini_stats_fd, "%f, ", elapsed);
2721 fprintf (mini_stats_fd, "]");
2722 if (no_opt_time > 0.0) {
2723 fprintf (mini_stats_fd, ", \n[");
2724 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++)
2725 fprintf (mini_stats_fd, "%f,", no_opt_time);
2726 fprintf (mini_stats_fd, "]");
2728 fprintf (mini_stats_fd, ");\n");
2729 } else {
2730 for (i = 0; i < count; ++i) {
2731 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2732 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
2733 method = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
2735 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2736 mono_destroy_compile (cfg);
2739 } else {
2740 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2741 mono_destroy_compile (cfg);
2743 #endif
2745 mini_cleanup (domain);
2746 return 0;
2750 * mono_jit_init:
2752 MonoDomain *
2753 mono_jit_init (const char *file)
2755 return mini_init (file, NULL);
2759 * mono_jit_init_version:
2760 * \param domain_name the name of the root domain
2761 * \param runtime_version the version of the runtime to load
2763 * Use this version when you want to force a particular runtime
2764 * version to be used. By default Mono will pick the runtime that is
2765 * referenced by the initial assembly (specified in \p file), this
2766 * routine allows programmers to specify the actual runtime to be used
2767 * as the initial runtime is inherited by all future assemblies loaded
2768 * (since Mono does not support having more than one mscorlib runtime
2769 * loaded at once).
2771 * The \p runtime_version can be one of these strings: "v4.0.30319" for
2772 * desktop, "mobile" for mobile or "moonlight" for Silverlight compat.
2773 * If an unrecognized string is input, the vm will default to desktop.
2775 * \returns the \c MonoDomain representing the domain where the assembly
2776 * was loaded.
2778 MonoDomain *
2779 mono_jit_init_version (const char *domain_name, const char *runtime_version)
2781 return mini_init (domain_name, runtime_version);
2785 * mono_jit_cleanup:
2787 void
2788 mono_jit_cleanup (MonoDomain *domain)
2790 MONO_ENTER_GC_UNSAFE;
2791 mono_thread_manage ();
2793 mini_cleanup (domain);
2794 MONO_EXIT_GC_UNSAFE;
2797 void
2798 mono_jit_set_aot_only (gboolean val)
2800 mono_aot_only = val;
2801 mono_ee_features.use_aot_trampolines = val;
2804 static void
2805 mono_runtime_set_execution_mode_full (MonoEEMode mode, gboolean override)
2807 static gboolean mode_initialized = FALSE;
2808 if (mode_initialized && !override)
2809 return;
2811 mode_initialized = TRUE;
2812 memset (&mono_ee_features, 0, sizeof (mono_ee_features));
2814 switch (mode) {
2815 case MONO_AOT_MODE_LLVMONLY:
2816 mono_aot_only = TRUE;
2817 mono_llvm_only = TRUE;
2819 mono_ee_features.use_aot_trampolines = TRUE;
2820 break;
2822 case MONO_AOT_MODE_FULL:
2823 mono_aot_only = TRUE;
2825 mono_ee_features.use_aot_trampolines = TRUE;
2826 break;
2828 case MONO_AOT_MODE_HYBRID:
2829 mono_set_generic_sharing_vt_supported (TRUE);
2830 mono_set_partial_sharing_supported (TRUE);
2831 break;
2833 case MONO_AOT_MODE_INTERP:
2834 mono_aot_only = TRUE;
2835 mono_use_interpreter = TRUE;
2837 mono_ee_features.use_aot_trampolines = TRUE;
2838 break;
2840 case MONO_AOT_MODE_INTERP_LLVMONLY:
2841 mono_aot_only = TRUE;
2842 mono_use_interpreter = TRUE;
2843 mono_llvm_only = TRUE;
2845 mono_ee_features.force_use_interpreter = TRUE;
2846 break;
2848 case MONO_AOT_MODE_LLVMONLY_INTERP:
2849 mono_aot_only = TRUE;
2850 mono_use_interpreter = TRUE;
2851 mono_llvm_only = TRUE;
2852 break;
2854 case MONO_EE_MODE_INTERP:
2855 mono_check_interp_supported ();
2856 mono_use_interpreter = TRUE;
2858 mono_ee_features.force_use_interpreter = TRUE;
2859 break;
2861 case MONO_AOT_MODE_NORMAL:
2862 case MONO_AOT_MODE_NONE:
2863 break;
2865 default:
2866 g_error ("Unknown execution-mode %d", mode);
2871 static void
2872 mono_runtime_set_execution_mode (MonoEEMode mode)
2874 mono_runtime_set_execution_mode_full (mode, TRUE);
2878 * mono_jit_set_aot_mode:
2880 void
2881 mono_jit_set_aot_mode (MonoAotMode mode)
2883 /* we don't want to set mono_aot_mode twice */
2884 static gboolean inited;
2886 g_assert (!inited);
2887 mono_aot_mode = mode;
2888 inited = TRUE;
2890 mono_runtime_set_execution_mode ((MonoEEMode)mode);
2893 mono_bool
2894 mono_jit_aot_compiling (void)
2896 return mono_compile_aot;
2900 * mono_jit_set_trace_options:
2901 * \param options string representing the trace options
2902 * Set the options of the tracing engine. This function can be called before initializing
2903 * the mono runtime. See the --trace mono(1) manpage for the options format.
2905 * \returns TRUE if the options were parsed and set correctly, FALSE otherwise.
2907 gboolean
2908 mono_jit_set_trace_options (const char* options)
2910 MonoCallSpec *trace_opt = mono_trace_set_options (options);
2911 if (trace_opt == NULL)
2912 return FALSE;
2913 mono_jit_trace_calls = trace_opt;
2914 return TRUE;
2918 * mono_set_signal_chaining:
2920 * Enable/disable signal chaining. This should be called before \c mono_jit_init.
2921 * If signal chaining is enabled, the runtime saves the original signal handlers before
2922 * installing its own handlers, and calls the original ones in the following cases:
2923 * - a \c SIGSEGV / \c SIGABRT signal received while executing native (i.e. not JITted) code.
2924 * - \c SIGPROF
2925 * - \c SIGFPE
2926 * - \c SIGQUIT
2927 * - \c SIGUSR2
2928 * Signal chaining only works on POSIX platforms.
2930 void
2931 mono_set_signal_chaining (gboolean chain_signals)
2933 mono_do_signal_chaining = chain_signals;
2937 * mono_set_crash_chaining:
2939 * Enable/disable crash chaining due to signals. When a fatal signal is delivered and
2940 * Mono doesn't know how to handle it, it will invoke the crash handler. If chrash chaining
2941 * is enabled, it will first print its crash information and then try to chain with the native handler.
2943 void
2944 mono_set_crash_chaining (gboolean chain_crashes)
2946 mono_do_crash_chaining = chain_crashes;
2950 * mono_parse_options_from:
2951 * \param options string containing strings
2952 * \param ref_argc pointer to the \c argc variable that might be updated
2953 * \param ref_argv pointer to the \c argv string vector variable that might be updated
2955 * This function parses the contents of the \c MONO_ENV_OPTIONS
2956 * environment variable as if they were parsed by a command shell
2957 * splitting the contents by spaces into different elements of the
2958 * \p argv vector. This method supports quoting with both the " and '
2959 * characters. Inside quoting, spaces and tabs are significant,
2960 * otherwise, they are considered argument separators.
2962 * The \ character can be used to escape the next character which will
2963 * be added to the current element verbatim. Typically this is used
2964 * inside quotes. If the quotes are not balanced, this method
2966 * If the environment variable is empty, no changes are made
2967 * to the values pointed by \p ref_argc and \p ref_argv.
2969 * Otherwise the \p ref_argv is modified to point to a new array that contains
2970 * all the previous elements contained in the vector, plus the values parsed.
2971 * The \p argc is updated to match the new number of parameters.
2973 * \returns The value NULL is returned on success, otherwise a \c g_strdup allocated
2974 * string is returned (this is an alias to \c malloc under normal circumstances) that
2975 * contains the error message that happened during parsing.
2977 char *
2978 mono_parse_options_from (const char *options, int *ref_argc, char **ref_argv [])
2980 return mono_parse_options (options, ref_argc, ref_argv, TRUE);
2983 static void
2984 merge_parsed_options (GPtrArray *parsed_options, int *ref_argc, char **ref_argv [], gboolean prepend)
2986 int argc = *ref_argc;
2987 char **argv = *ref_argv;
2989 if (parsed_options->len > 0){
2990 int new_argc = parsed_options->len + argc;
2991 char **new_argv = g_new (char *, new_argc + 1);
2992 guint i;
2993 guint j;
2995 new_argv [0] = argv [0];
2997 i = 1;
2998 if (prepend){
2999 /* First the environment variable settings, to allow the command line options to override */
3000 for (i = 0; i < parsed_options->len; i++)
3001 new_argv [i+1] = (char *)g_ptr_array_index (parsed_options, i);
3002 i++;
3004 for (j = 1; j < argc; j++)
3005 new_argv [i++] = argv [j];
3006 if (!prepend){
3007 for (j = 0; j < parsed_options->len; j++)
3008 new_argv [i++] = (char *)g_ptr_array_index (parsed_options, j);
3010 new_argv [i] = NULL;
3012 *ref_argc = new_argc;
3013 *ref_argv = new_argv;
3017 static char *
3018 mono_parse_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3020 if (options == NULL)
3021 return NULL;
3023 GPtrArray *array = g_ptr_array_new ();
3024 GString *buffer = g_string_new ("");
3025 const char *p;
3026 gboolean in_quotes = FALSE;
3027 char quote_char = '\0';
3029 for (p = options; *p; p++){
3030 switch (*p){
3031 case ' ': case '\t': case '\n':
3032 if (!in_quotes) {
3033 if (buffer->len != 0){
3034 g_ptr_array_add (array, g_strdup (buffer->str));
3035 g_string_truncate (buffer, 0);
3037 } else {
3038 g_string_append_c (buffer, *p);
3040 break;
3041 case '\\':
3042 if (p [1]){
3043 g_string_append_c (buffer, p [1]);
3044 p++;
3046 break;
3047 case '\'':
3048 case '"':
3049 if (in_quotes) {
3050 if (quote_char == *p)
3051 in_quotes = FALSE;
3052 else
3053 g_string_append_c (buffer, *p);
3054 } else {
3055 in_quotes = TRUE;
3056 quote_char = *p;
3058 break;
3059 default:
3060 g_string_append_c (buffer, *p);
3061 break;
3064 if (in_quotes)
3065 return g_strdup_printf ("Unmatched quotes in value: [%s]\n", options);
3067 if (buffer->len != 0)
3068 g_ptr_array_add (array, g_strdup (buffer->str));
3069 g_string_free (buffer, TRUE);
3071 merge_parsed_options (array, ref_argc, ref_argv, prepend);
3072 g_ptr_array_free (array, TRUE);
3074 return NULL;
3077 #if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
3078 #include <shellapi.h>
3080 static char *
3081 mono_win32_parse_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3083 int argc;
3084 gunichar2 **argv;
3085 gunichar2 *optionsw;
3087 if (!options)
3088 return NULL;
3090 GPtrArray *array = g_ptr_array_new ();
3091 optionsw = g_utf8_to_utf16 (options, -1, NULL, NULL, NULL);
3092 if (optionsw) {
3093 gunichar2 *p;
3094 gboolean in_quotes = FALSE;
3095 gunichar2 quote_char = L'\0';
3096 for (p = optionsw; *p; p++){
3097 switch (*p){
3098 case L'\n':
3099 if (!in_quotes)
3100 *p = L' ';
3101 break;
3102 case L'\'':
3103 case L'"':
3104 if (in_quotes) {
3105 if (quote_char == *p)
3106 in_quotes = FALSE;
3107 } else {
3108 in_quotes = TRUE;
3109 quote_char = *p;
3111 break;
3115 argv = CommandLineToArgvW (optionsw, &argc);
3116 if (argv) {
3117 for (int i = 0; i < argc; i++)
3118 g_ptr_array_add (array, g_utf16_to_utf8 (argv[i], -1, NULL, NULL, NULL));
3120 LocalFree (argv);
3123 g_free (optionsw);
3126 merge_parsed_options (array, ref_argc, ref_argv, prepend);
3127 g_ptr_array_free (array, TRUE);
3129 return NULL;
3132 static inline char *
3133 mono_parse_response_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3135 return mono_win32_parse_options (options, ref_argc, ref_argv, prepend);
3137 #else
3138 static inline char *
3139 mono_parse_response_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3141 return mono_parse_options (options, ref_argc, ref_argv, prepend);
3143 #endif
3146 * mono_parse_env_options:
3147 * \param ref_argc pointer to the \c argc variable that might be updated
3148 * \param ref_argv pointer to the \c argv string vector variable that might be updated
3150 * This function parses the contents of the \c MONO_ENV_OPTIONS
3151 * environment variable as if they were parsed by a command shell
3152 * splitting the contents by spaces into different elements of the
3153 * \p argv vector. This method supports quoting with both the " and '
3154 * characters. Inside quoting, spaces and tabs are significant,
3155 * otherwise, they are considered argument separators.
3157 * The \ character can be used to escape the next character which will
3158 * be added to the current element verbatim. Typically this is used
3159 * inside quotes. If the quotes are not balanced, this method
3161 * If the environment variable is empty, no changes are made
3162 * to the values pointed by \p ref_argc and \p ref_argv.
3164 * Otherwise the \p ref_argv is modified to point to a new array that contains
3165 * all the previous elements contained in the vector, plus the values parsed.
3166 * The \p argc is updated to match the new number of parameters.
3168 * If there is an error parsing, this method will terminate the process by
3169 * calling exit(1).
3171 * An alternative to this method that allows an arbitrary string to be parsed
3172 * and does not exit on error is the `api:mono_parse_options_from`.
3174 void
3175 mono_parse_env_options (int *ref_argc, char **ref_argv [])
3177 char *ret;
3179 char *env_options = g_getenv ("MONO_ENV_OPTIONS");
3180 if (env_options == NULL)
3181 return;
3182 ret = mono_parse_options_from (env_options, ref_argc, ref_argv);
3183 g_free (env_options);
3184 if (ret == NULL)
3185 return;
3186 fprintf (stderr, "%s", ret);
3187 exit (1);