[LoongArch64] Part-5:add loongarch support in some files for LoongArch64. (#21769)
[mono-project.git] / mono / mini / driver.c
blob6a48f075dcfd90df3528c94eccaeacf6e1dbbba2
1 /**
2 * \file
3 * The new mono JIT compiler.
5 * Author:
6 * Paolo Molaro (lupus@ximian.com)
7 * Dietmar Maurer (dietmar@ximian.com)
9 * (C) 2002-2003 Ximian, Inc.
10 * (C) 2003-2006 Novell, Inc.
11 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14 #include <config.h>
15 #include <signal.h>
16 #if HAVE_SCHED_SETAFFINITY
17 #include <sched.h>
18 #endif
19 #ifdef HAVE_UNISTD_H
20 #include <unistd.h>
21 #endif
23 #include <mono/metadata/assembly-internals.h>
24 #include <mono/metadata/image-internals.h>
25 #include <mono/metadata/loader.h>
26 #include <mono/metadata/tabledefs.h>
27 #include <mono/metadata/class.h>
28 #include <mono/metadata/object.h>
29 #include <mono/metadata/exception.h>
30 #include <mono/metadata/opcodes.h>
31 #include <mono/metadata/mono-endian.h>
32 #include <mono/metadata/tokentype.h>
33 #include <mono/metadata/reflection-internals.h>
34 #include <mono/metadata/tabledefs.h>
35 #include <mono/metadata/threads.h>
36 #include <mono/metadata/marshal.h>
37 #include <mono/metadata/appdomain.h>
38 #include <mono/metadata/debug-helpers.h>
39 #include <mono/metadata/profiler-private.h>
40 #include <mono/metadata/mono-config.h>
41 #include <mono/metadata/environment.h>
42 #include <mono/metadata/environment-internals.h>
43 #include <mono/metadata/verify.h>
44 #include <mono/metadata/verify-internals.h>
45 #include <mono/metadata/mono-debug.h>
46 #include <mono/metadata/security-manager.h>
47 #include <mono/metadata/security-core-clr.h>
48 #include <mono/metadata/gc-internals.h>
49 #include <mono/metadata/coree.h>
50 #include <mono/metadata/attach.h>
51 #include <mono/metadata/w32process.h>
52 #include "mono/utils/mono-counters.h"
53 #include "mono/utils/mono-hwcap.h"
54 #include "mono/utils/mono-logger-internals.h"
55 #include "mono/utils/options.h"
56 #include "mono/metadata/w32handle.h"
57 #include "mono/metadata/callspec.h"
58 #include "mono/metadata/custom-attrs-internals.h"
59 #include <mono/utils/w32subset.h>
61 #include "mini.h"
62 #include "jit.h"
63 #include "aot-compiler.h"
64 #include "aot-runtime.h"
65 #include "mini-runtime.h"
66 #include "interp/interp.h"
68 #include <string.h>
69 #include <ctype.h>
70 #include <locale.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 (int mode);
80 static void mono_runtime_set_execution_mode_full (int 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 char name [6];
240 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;
286 gboolean need_comma;
288 need_comma = FALSE;
289 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
290 if (flags & (1 << i) && optflag_get_name (i)) {
291 if (need_comma)
292 g_string_append_c (str, ',');
293 g_string_append (str, optflag_get_name (i));
294 need_comma = TRUE;
297 return g_string_free (str, FALSE);
300 static const guint32
301 opt_sets [] = {
303 MONO_OPT_PEEPHOLE,
304 MONO_OPT_BRANCH,
305 MONO_OPT_CFOLD,
306 MONO_OPT_FCMOV,
307 MONO_OPT_ALIAS_ANALYSIS,
308 #ifdef MONO_ARCH_SIMD_INTRINSICS
309 MONO_OPT_SIMD | MONO_OPT_INTRINS,
310 MONO_OPT_SSE2,
311 MONO_OPT_SIMD | MONO_OPT_SSE2 | MONO_OPT_INTRINS,
312 #endif
313 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS,
314 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS | MONO_OPT_ALIAS_ANALYSIS,
315 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS,
316 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP,
317 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_CFOLD,
318 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE,
319 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_ALIAS_ANALYSIS,
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,
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_TAILCALL,
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_SSA,
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,
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_CMOV,
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_EXCEPTION | 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,
327 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,
328 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,
329 DEFAULT_OPTIMIZATIONS,
332 static const guint32
333 interp_opt_sets [] = {
334 INTERP_OPT_NONE,
335 INTERP_OPT_INLINE,
336 INTERP_OPT_CPROP,
337 INTERP_OPT_SUPER_INSTRUCTIONS,
338 INTERP_OPT_INLINE | INTERP_OPT_CPROP,
339 INTERP_OPT_INLINE | INTERP_OPT_SUPER_INSTRUCTIONS,
340 INTERP_OPT_CPROP | INTERP_OPT_SUPER_INSTRUCTIONS,
341 INTERP_OPT_INLINE | INTERP_OPT_CPROP | INTERP_OPT_SUPER_INSTRUCTIONS | INTERP_OPT_BBLOCKS,
344 static const char* const
345 interp_opflags_names [] = {
346 "inline",
347 "cprop",
348 "super-insn",
349 "bblocks"
352 static const char*
353 interp_optflag_get_name (guint32 i)
355 g_assert (i < G_N_ELEMENTS (interp_opflags_names));
356 return interp_opflags_names [i];
359 static char*
360 interp_opt_descr (guint32 flags)
362 GString *str = g_string_new ("");
363 int i;
364 gboolean need_comma;
366 need_comma = FALSE;
367 for (i = 0; i < G_N_ELEMENTS (interp_opflags_names); ++i) {
368 if (flags & (1 << i) && interp_optflag_get_name (i)) {
369 if (need_comma)
370 g_string_append_c (str, ',');
371 g_string_append (str, interp_optflag_get_name (i));
372 need_comma = TRUE;
375 return g_string_free (str, FALSE);
378 typedef int (*TestMethod) (void);
380 #if 0
381 static void
382 domain_dump_native_code (MonoDomain *domain) {
383 // need to poke into the domain, move to metadata/domain.c
384 // need to empty jit_info_table and code_mp
386 #endif
388 static gboolean do_regression_retries;
389 static int regression_test_skip_index;
392 static gboolean
393 method_should_be_regression_tested (MonoMethod *method, gboolean interp)
395 ERROR_DECL (error);
397 if (strncmp (method->name, "test_", 5) != 0)
398 return FALSE;
400 static gboolean filter_method_init = FALSE;
401 static const char *filter_method = NULL;
403 if (!filter_method_init) {
404 filter_method = g_getenv ("REGRESSION_FILTER_METHOD");
405 filter_method_init = TRUE;
408 if (filter_method) {
409 const char *name = filter_method;
411 if ((strchr (name, '.') > name) || strchr (name, ':')) {
412 MonoMethodDesc *desc = mono_method_desc_new (name, TRUE);
413 gboolean res = mono_method_desc_full_match (desc, method);
414 mono_method_desc_free (desc);
415 return res;
416 } else {
417 return strcmp (method->name, name) == 0;
421 MonoCustomAttrInfo* ainfo = mono_custom_attrs_from_method_checked (method, error);
422 mono_error_cleanup (error);
423 if (!ainfo)
424 return TRUE;
426 int j;
427 for (j = 0; j < ainfo->num_attrs; ++j) {
428 MonoCustomAttrEntry *centry = &ainfo->attrs [j];
429 if (centry->ctor == NULL)
430 continue;
432 MonoClass *klass = centry->ctor->klass;
433 if (strcmp (m_class_get_name (klass), "CategoryAttribute") || mono_method_signature_internal (centry->ctor)->param_count != 1)
434 continue;
436 gpointer *typed_args, *named_args;
437 int num_named_args;
438 CattrNamedArg *arginfo;
440 mono_reflection_create_custom_attr_data_args_noalloc (
441 mono_defaults.corlib, centry->ctor, centry->data, centry->data_size,
442 &typed_args, &named_args, &num_named_args, &arginfo, error);
443 if (!is_ok (error))
444 continue;
446 const char *arg = (const char*)typed_args [0];
447 mono_metadata_decode_value (arg, &arg);
448 char *utf8_str = (char*)arg; //this points into image memory that is constant
449 g_free (typed_args);
450 g_free (named_args);
451 g_free (arginfo);
453 if (interp && !strcmp (utf8_str, "!INTERPRETER")) {
454 g_print ("skip %s...\n", method->name);
455 return FALSE;
458 #if HOST_WASM
459 if (!strcmp (utf8_str, "!WASM")) {
460 g_print ("skip %s...\n", method->name);
461 return FALSE;
463 #endif
464 if (mono_aot_mode == MONO_AOT_MODE_FULL && !strcmp (utf8_str, "!FULLAOT")) {
465 g_print ("skip %s...\n", method->name);
466 return FALSE;
469 if ((mono_aot_mode == MONO_AOT_MODE_INTERP_LLVMONLY || mono_aot_mode == MONO_AOT_MODE_LLVMONLY) && !strcmp (utf8_str, "!BITCODE")) {
470 g_print ("skip %s...\n", method->name);
471 return FALSE;
475 return TRUE;
478 static void
479 mini_regression_step (MonoImage *image, int verbose, int *total_run, int *total,
480 guint32 opt_flags,
481 GTimer *timer, MonoDomain *domain)
483 int result, expected, failed, cfailed, run, code_size;
484 double elapsed, comp_time, start_time;
485 char *n;
486 int i;
488 mono_set_defaults (verbose, opt_flags);
489 n = mono_opt_descr (opt_flags);
490 g_print ("Test run: image=%s, opts=%s\n", mono_image_get_filename (image), n);
491 g_free (n);
492 cfailed = failed = run = code_size = 0;
493 comp_time = elapsed = 0.0;
494 int local_skip_index = 0;
496 /* fixme: ugly hack - delete all previously compiled methods */
497 if (domain_jit_info (domain)) {
498 g_hash_table_destroy (domain_jit_info (domain)->jit_trampoline_hash);
499 domain_jit_info (domain)->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
500 mono_internal_hash_table_destroy (&(domain->jit_code_hash));
501 mono_jit_code_hash_init (&(domain->jit_code_hash));
504 g_timer_start (timer);
505 if (mini_stats_fd)
506 fprintf (mini_stats_fd, "[");
507 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
508 ERROR_DECL (error);
509 MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
510 if (!method) {
511 mono_error_cleanup (error); /* FIXME don't swallow the error */
512 continue;
514 if (method_should_be_regression_tested (method, FALSE)) {
515 MonoCompile *cfg = NULL;
516 TestMethod func = NULL;
518 expected = atoi (method->name + 5);
519 run++;
520 start_time = g_timer_elapsed (timer, NULL);
522 #ifdef DISABLE_JIT
523 #ifdef MONO_USE_AOT_COMPILER
524 ERROR_DECL (error);
525 func = (TestMethod)mono_aot_get_method (mono_get_root_domain (), method, error);
526 mono_error_cleanup (error);
527 #else
528 g_error ("No JIT or AOT available, regression testing not possible!");
529 #endif
531 #else
532 comp_time -= start_time;
533 cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, opt_flags), mono_get_root_domain (), JIT_FLAG_RUN_CCTORS, 0, -1);
534 comp_time += g_timer_elapsed (timer, NULL);
535 if (cfg->exception_type == MONO_EXCEPTION_NONE) {
536 #ifdef MONO_USE_AOT_COMPILER
537 ERROR_DECL (error);
538 func = (TestMethod)mono_aot_get_method (mono_get_root_domain (), method, error);
539 mono_error_cleanup (error);
540 if (!func) {
541 func = (TestMethod)MINI_ADDR_TO_FTNPTR (cfg->native_code);
543 #else
544 func = (TestMethod)(gpointer)cfg->native_code;
545 func = MINI_ADDR_TO_FTNPTR (func);
546 #endif
547 func = (TestMethod)mono_create_ftnptr (mono_get_root_domain (), (gpointer)func);
549 #endif
551 if (func) {
552 if (do_regression_retries) {
553 ++local_skip_index;
555 if(local_skip_index <= regression_test_skip_index)
556 continue;
557 ++regression_test_skip_index;
560 if (verbose >= 2)
561 g_print ("Running '%s' ...\n", method->name);
563 #if HOST_WASM
564 //WASM AOT injects dummy args and we must call with exact signatures
565 int (*func_2)(int) = (int (*)(int))(void*)func;
566 result = func_2 (-1);
567 #else
568 result = func ();
569 #endif
570 if (result != expected) {
571 failed++;
572 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
574 if (cfg) {
575 code_size += cfg->code_len;
576 mono_destroy_compile (cfg);
578 } else {
579 cfailed++;
580 g_print ("Test '%s' failed compilation.\n", method->name);
582 if (mini_stats_fd)
583 fprintf (mini_stats_fd, "%f, ",
584 g_timer_elapsed (timer, NULL) - start_time);
587 if (mini_stats_fd)
588 fprintf (mini_stats_fd, "],\n");
589 g_timer_stop (timer);
590 elapsed = g_timer_elapsed (timer, NULL);
591 if (failed > 0 || cfailed > 0){
592 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n",
593 run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
594 } else {
595 g_print ("Results: total tests: %d, all pass \n", run);
598 g_print ("Elapsed time: %f secs (%f, %f), Code size: %d\n\n", elapsed,
599 elapsed - comp_time, comp_time, code_size);
600 *total += failed + cfailed;
601 *total_run += run;
604 static int
605 mini_regression (MonoImage *image, int verbose, int *total_run)
607 guint32 i, opt;
608 MonoMethod *method;
609 char *n;
610 GTimer *timer = g_timer_new ();
611 MonoDomain *domain = mono_domain_get ();
612 guint32 exclude = 0;
613 int total;
615 /* Note: mono_hwcap_init () called in mono_init () before we get here. */
616 mono_arch_cpu_optimizations (&exclude);
618 if (mini_stats_fd) {
619 fprintf (mini_stats_fd, "$stattitle = \'Mono Benchmark Results (various optimizations)\';\n");
621 fprintf (mini_stats_fd, "$graph->set_legend(qw(");
622 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); opt++) {
623 guint32 opt_flags = opt_sets [opt];
624 n = mono_opt_descr (opt_flags);
625 if (!n [0])
626 n = (char *)"none";
627 if (opt)
628 fprintf (mini_stats_fd, " ");
629 fprintf (mini_stats_fd, "%s", n);
633 fprintf (mini_stats_fd, "));\n");
635 fprintf (mini_stats_fd, "@data = (\n");
636 fprintf (mini_stats_fd, "[");
639 /* load the metadata */
640 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
641 ERROR_DECL (error);
642 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
643 if (!method) {
644 mono_error_cleanup (error);
645 continue;
647 mono_class_init_internal (method->klass);
649 if (!strncmp (method->name, "test_", 5) && mini_stats_fd) {
650 fprintf (mini_stats_fd, "\"%s\",", method->name);
653 if (mini_stats_fd)
654 fprintf (mini_stats_fd, "],\n");
657 total = 0;
658 *total_run = 0;
659 if (mono_do_single_method_regression) {
660 GSList *iter;
662 mini_regression_step (image, verbose, total_run, &total,
664 timer, domain);
665 if (total)
666 return total;
667 g_print ("Single method regression: %d methods\n", g_slist_length (mono_single_method_list));
669 for (iter = mono_single_method_list; iter; iter = g_slist_next (iter)) {
670 char *method_name;
672 mono_current_single_method = (MonoMethod *)iter->data;
674 method_name = mono_method_full_name (mono_current_single_method, TRUE);
675 g_print ("Current single method: %s\n", method_name);
676 g_free (method_name);
678 mini_regression_step (image, verbose, total_run, &total,
680 timer, domain);
681 if (total)
682 return total;
684 } else {
685 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); ++opt) {
686 /* builtin-types.cs & aot-tests.cs need OPT_INTRINS enabled */
687 if (!strcmp ("builtin-types", image->assembly_name) || !strcmp ("aot-tests", image->assembly_name))
688 if (!(opt_sets [opt] & MONO_OPT_INTRINS))
689 continue;
691 //we running in AOT only, it makes no sense to try multiple flags
692 if ((mono_aot_mode == MONO_AOT_MODE_FULL || mono_aot_mode == MONO_AOT_MODE_LLVMONLY) && opt_sets [opt] != DEFAULT_OPTIMIZATIONS) {
693 continue;
696 mini_regression_step (image, verbose, total_run, &total,
697 opt_sets [opt] & ~exclude,
698 timer, domain);
702 if (mini_stats_fd) {
703 fprintf (mini_stats_fd, ");\n");
704 fflush (mini_stats_fd);
707 g_timer_destroy (timer);
708 return total;
711 static int
712 mini_regression_list (int verbose, int count, char *images [])
714 int i, total, total_run, run;
715 MonoAssembly *ass;
717 total_run = total = 0;
718 for (i = 0; i < count; ++i) {
719 MonoAssemblyOpenRequest req;
720 mono_assembly_request_prepare_open (&req, MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_get_root_domain ()));
721 ass = mono_assembly_request_open (images [i], &req, NULL);
722 if (!ass) {
723 g_warning ("failed to load assembly: %s", images [i]);
724 continue;
726 total += mini_regression (mono_assembly_get_image_internal (ass), verbose, &run);
727 total_run += run;
729 if (total > 0){
730 g_print ("Overall results: tests: %d, failed: %d, opt combinations: %d (pass: %.2f%%)\n",
731 total_run, total, (int)G_N_ELEMENTS (opt_sets), 100.0*(total_run-total)/total_run);
732 } else {
733 g_print ("Overall results: tests: %d, 100%% pass, opt combinations: %d\n",
734 total_run, (int)G_N_ELEMENTS (opt_sets));
737 return total;
740 static void
741 interp_regression_step (MonoImage *image, int verbose, int *total_run, int *total, const guint32 *opt_flags, GTimer *timer, MonoDomain *domain)
743 int result, expected, failed, cfailed, run;
744 double elapsed, transform_time;
745 int i;
746 MonoObject *result_obj;
747 int local_skip_index = 0;
749 const char *n = NULL;
750 if (opt_flags) {
751 mini_get_interp_callbacks ()->set_optimizations (*opt_flags);
752 n = interp_opt_descr (*opt_flags);
753 } else {
754 n = mono_interp_opts_string;
756 g_print ("Test run: image=%s, opts=%s\n", mono_image_get_filename (image), n);
758 cfailed = failed = run = 0;
759 transform_time = elapsed = 0.0;
761 mini_get_interp_callbacks ()->invalidate_transformed (domain);
763 g_timer_start (timer);
764 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
765 ERROR_DECL (error);
766 MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
767 if (!method) {
768 mono_error_cleanup (error); /* FIXME don't swallow the error */
769 continue;
772 if (method_should_be_regression_tested (method, TRUE)) {
773 ERROR_DECL (interp_error);
774 MonoObject *exc = NULL;
776 if (do_regression_retries) {
777 ++local_skip_index;
779 if(local_skip_index <= regression_test_skip_index)
780 continue;
781 ++regression_test_skip_index;
784 result_obj = mini_get_interp_callbacks ()->runtime_invoke (method, NULL, NULL, &exc, interp_error);
785 if (!is_ok (interp_error)) {
786 cfailed++;
787 g_print ("Test '%s' execution failed.\n", method->name);
788 } else if (exc != NULL) {
789 g_print ("Exception in Test '%s' occurred:\n", method->name);
790 mono_object_describe (exc);
791 run++;
792 failed++;
793 } else {
794 result = *(gint32 *) mono_object_unbox_internal (result_obj);
795 expected = atoi (method->name + 5); // FIXME: oh no.
796 run++;
798 if (result != expected) {
799 failed++;
800 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
805 g_timer_stop (timer);
806 elapsed = g_timer_elapsed (timer, NULL);
807 if (failed > 0 || cfailed > 0){
808 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n",
809 run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
810 } else {
811 g_print ("Results: total tests: %d, all pass \n", run);
814 g_print ("Elapsed time: %f secs (%f, %f)\n\n", elapsed,
815 elapsed - transform_time, transform_time);
816 *total += failed + cfailed;
817 *total_run += run;
820 static int
821 interp_regression (MonoImage *image, int verbose, int *total_run)
823 MonoMethod *method;
824 GTimer *timer = g_timer_new ();
825 MonoDomain *domain = mono_domain_get ();
826 guint32 i;
827 int total;
829 /* load the metadata */
830 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
831 ERROR_DECL (error);
832 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
833 if (!method) {
834 mono_error_cleanup (error);
835 continue;
837 mono_class_init_internal (method->klass);
840 total = 0;
841 *total_run = 0;
843 if (mono_interp_opts_string) {
844 /* explicit option requested*/
845 interp_regression_step (image, verbose, total_run, &total, NULL, timer, domain);
846 } else {
847 for (int opt = 0; opt < G_N_ELEMENTS (interp_opt_sets); ++opt)
848 interp_regression_step (image, verbose, total_run, &total, &interp_opt_sets [opt], timer, domain);
851 g_timer_destroy (timer);
852 return total;
855 /* TODO: merge this code with the regression harness of the JIT */
856 static int
857 mono_interp_regression_list (int verbose, int count, char *images [])
859 int i, total, total_run, run;
861 total_run = total = 0;
862 for (i = 0; i < count; ++i) {
863 MonoAssemblyOpenRequest req;
864 mono_assembly_request_prepare_open (&req, MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_get_root_domain ()));
865 MonoAssembly *ass = mono_assembly_request_open (images [i], &req, NULL);
866 if (!ass) {
867 g_warning ("failed to load assembly: %s", images [i]);
868 continue;
870 total += interp_regression (mono_assembly_get_image_internal (ass), verbose, &run);
871 total_run += run;
873 if (total > 0) {
874 g_print ("Overall results: tests: %d, failed: %d (pass: %.2f%%)\n", total_run, total, 100.0*(total_run-total)/total_run);
875 } else {
876 g_print ("Overall results: tests: %d, 100%% pass\n", total_run);
879 return total;
883 #ifdef MONO_JIT_INFO_TABLE_TEST
884 typedef struct _JitInfoData
886 guint start;
887 guint length;
888 MonoJitInfo *ji;
889 struct _JitInfoData *next;
890 } JitInfoData;
892 typedef struct
894 guint start;
895 guint length;
896 int num_datas;
897 JitInfoData *data;
898 } Region;
900 typedef struct
902 int num_datas;
903 int num_regions;
904 Region *regions;
905 int num_frees;
906 JitInfoData *frees;
907 } ThreadData;
909 static int num_threads;
910 static ThreadData *thread_datas;
911 static MonoDomain *test_domain;
913 static JitInfoData*
914 alloc_random_data (Region *region)
916 JitInfoData **data;
917 JitInfoData *prev;
918 guint prev_end;
919 guint next_start;
920 guint max_len;
921 JitInfoData *d;
922 int num_retries = 0;
923 int pos, i;
925 restart:
926 prev = NULL;
927 data = &region->data;
928 pos = random () % (region->num_datas + 1);
929 i = 0;
930 while (*data != NULL) {
931 if (i++ == pos)
932 break;
933 prev = *data;
934 data = &(*data)->next;
937 if (prev == NULL)
938 g_assert (*data == region->data);
939 else
940 g_assert (prev->next == *data);
942 if (prev == NULL)
943 prev_end = region->start;
944 else
945 prev_end = prev->start + prev->length;
947 if (*data == NULL)
948 next_start = region->start + region->length;
949 else
950 next_start = (*data)->start;
952 g_assert (prev_end <= next_start);
954 max_len = next_start - prev_end;
955 if (max_len < 128) {
956 if (++num_retries >= 10)
957 return NULL;
958 goto restart;
960 if (max_len > 1024)
961 max_len = 1024;
963 d = g_new0 (JitInfoData, 1);
964 d->start = prev_end + random () % (max_len / 2);
965 d->length = random () % MIN (max_len, next_start - d->start) + 1;
967 g_assert (d->start >= prev_end && d->start + d->length <= next_start);
969 d->ji = g_new0 (MonoJitInfo, 1);
970 d->ji->d.method = (MonoMethod*) 0xABadBabe;
971 d->ji->code_start = (gpointer)(gulong) d->start;
972 d->ji->code_size = d->length;
973 d->ji->cas_inited = 1; /* marks an allocated jit info */
975 d->next = *data;
976 *data = d;
978 ++region->num_datas;
980 return d;
983 static JitInfoData**
984 choose_random_data (Region *region)
986 int n;
987 int i;
988 JitInfoData **d;
990 g_assert (region->num_datas > 0);
992 n = random () % region->num_datas;
994 for (d = &region->data, i = 0;
995 i < n;
996 d = &(*d)->next, ++i)
999 return d;
1002 static Region*
1003 choose_random_region (ThreadData *td)
1005 return &td->regions [random () % td->num_regions];
1008 static ThreadData*
1009 choose_random_thread (void)
1011 return &thread_datas [random () % num_threads];
1014 static void
1015 free_jit_info_data (ThreadData *td, JitInfoData *free)
1017 free->next = td->frees;
1018 td->frees = free;
1020 if (++td->num_frees >= 1000) {
1021 int i;
1023 for (i = 0; i < 500; ++i)
1024 free = free->next;
1026 while (free->next != NULL) {
1027 JitInfoData *next = free->next->next;
1029 //g_free (free->next->ji);
1030 g_free (free->next);
1031 free->next = next;
1033 --td->num_frees;
1038 #define NUM_THREADS 8
1039 #define REGIONS_PER_THREAD 10
1040 #define REGION_SIZE 0x10000
1042 #define MAX_ADDR (REGION_SIZE * REGIONS_PER_THREAD * NUM_THREADS)
1044 #define MODE_ALLOC 1
1045 #define MODE_FREE 2
1047 static void
1048 test_thread_func (gpointer void_arg)
1050 ThreadData* td = (ThreadData*)void_arg;
1051 int mode = MODE_ALLOC;
1052 int i = 0;
1053 gulong lookup_successes = 0, lookup_failures = 0;
1054 MonoDomain *domain = test_domain;
1055 int thread_num = (int)(td - thread_datas);
1056 gboolean modify_thread = thread_num < NUM_THREADS / 2; /* only half of the threads modify the table */
1058 for (;;) {
1059 int alloc;
1060 int lookup = 1;
1062 if (td->num_datas == 0) {
1063 lookup = 0;
1064 alloc = 1;
1065 } else if (modify_thread && random () % 1000 < 5) {
1066 lookup = 0;
1067 if (mode == MODE_ALLOC)
1068 alloc = (random () % 100) < 70;
1069 else if (mode == MODE_FREE)
1070 alloc = (random () % 100) < 30;
1073 if (lookup) {
1074 /* modify threads sometimes look up their own jit infos */
1075 if (modify_thread && random () % 10 < 5) {
1076 Region *region = choose_random_region (td);
1078 if (region->num_datas > 0) {
1079 JitInfoData **data = choose_random_data (region);
1080 guint pos = (*data)->start + random () % (*data)->length;
1081 MonoJitInfo *ji;
1083 ji = mono_jit_info_table_find (domain, (char*)(gsize)pos);
1085 g_assert (ji->cas_inited);
1086 g_assert ((*data)->ji == ji);
1088 } else {
1089 int pos = random () % MAX_ADDR;
1090 char *addr = (char*)(uintptr_t)pos;
1091 MonoJitInfo *ji;
1093 ji = mono_jit_info_table_find (domain, addr);
1096 * FIXME: We are actually not allowed
1097 * to do this. By the time we examine
1098 * the ji another thread might already
1099 * have removed it.
1101 if (ji != NULL) {
1102 g_assert (addr >= (char*)ji->code_start && addr < (char*)ji->code_start + ji->code_size);
1103 ++lookup_successes;
1104 } else
1105 ++lookup_failures;
1107 } else if (alloc) {
1108 JitInfoData *data = alloc_random_data (choose_random_region (td));
1110 if (data != NULL) {
1111 mono_jit_info_table_add (domain, data->ji);
1113 ++td->num_datas;
1115 } else {
1116 Region *region = choose_random_region (td);
1118 if (region->num_datas > 0) {
1119 JitInfoData **data = choose_random_data (region);
1120 JitInfoData *free;
1122 mono_jit_info_table_remove (domain, (*data)->ji);
1124 //(*data)->ji->cas_inited = 0; /* marks a free jit info */
1126 free = *data;
1127 *data = (*data)->next;
1129 free_jit_info_data (td, free);
1131 --region->num_datas;
1132 --td->num_datas;
1136 if (++i % 100000 == 0) {
1137 int j;
1138 g_print ("num datas %d (%ld - %ld): %d", (int)(td - thread_datas),
1139 lookup_successes, lookup_failures, td->num_datas);
1140 for (j = 0; j < td->num_regions; ++j)
1141 g_print (" %d", td->regions [j].num_datas);
1142 g_print ("\n");
1145 if (td->num_datas < 100)
1146 mode = MODE_ALLOC;
1147 else if (td->num_datas > 2000)
1148 mode = MODE_FREE;
1153 static void
1154 small_id_thread_func (gpointer arg)
1156 MonoThread *thread = mono_thread_current ();
1157 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1159 g_print ("my small id is %d\n", (int)thread->small_id);
1160 mono_hazard_pointer_clear (hp, 1);
1161 sleep (3);
1162 g_print ("done %d\n", (int)thread->small_id);
1166 static void
1167 jit_info_table_test (MonoDomain *domain)
1169 ERROR_DECL (error);
1170 int i;
1172 g_print ("testing jit_info_table\n");
1174 num_threads = NUM_THREADS;
1175 thread_datas = g_new0 (ThreadData, num_threads);
1177 for (i = 0; i < num_threads; ++i) {
1178 int j;
1180 thread_datas [i].num_regions = REGIONS_PER_THREAD;
1181 thread_datas [i].regions = g_new0 (Region, REGIONS_PER_THREAD);
1183 for (j = 0; j < REGIONS_PER_THREAD; ++j) {
1184 thread_datas [i].regions [j].start = (num_threads * j + i) * REGION_SIZE;
1185 thread_datas [i].regions [j].length = REGION_SIZE;
1189 test_domain = domain;
1192 for (i = 0; i < 72; ++i)
1193 mono_thread_create (domain, small_id_thread_func, NULL);
1195 sleep (2);
1198 for (i = 0; i < num_threads; ++i) {
1199 mono_thread_create_checked (domain, (gpointer)test_thread_func, &thread_datas [i], error);
1200 mono_error_assert_ok (error);
1203 #endif
1205 enum {
1206 DO_BENCH,
1207 DO_REGRESSION,
1208 DO_SINGLE_METHOD_REGRESSION,
1209 DO_COMPILE,
1210 DO_EXEC,
1211 DO_DRAW,
1212 DO_DEBUGGER
1215 typedef struct CompileAllThreadArgs {
1216 MonoAssembly *ass;
1217 int verbose;
1218 guint32 opts;
1219 guint32 recompilation_times;
1220 } CompileAllThreadArgs;
1222 static void
1223 compile_all_methods_thread_main_inner (CompileAllThreadArgs *args)
1225 MonoAssembly *ass = args->ass;
1226 int verbose = args->verbose;
1227 MonoImage *image = mono_assembly_get_image_internal (ass);
1228 MonoMethod *method;
1229 MonoCompile *cfg;
1230 int i, count = 0, fail_count = 0;
1232 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
1233 ERROR_DECL (error);
1234 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1235 MonoMethodSignature *sig;
1237 if (mono_metadata_has_generic_params (image, token))
1238 continue;
1240 method = mono_get_method_checked (image, token, NULL, NULL, error);
1241 if (!method) {
1242 mono_error_cleanup (error); /* FIXME don't swallow the error */
1243 continue;
1245 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1246 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1247 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1248 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1249 continue;
1251 if (mono_class_is_gtd (method->klass))
1252 continue;
1253 sig = mono_method_signature_internal (method);
1254 if (!sig) {
1255 char * desc = mono_method_full_name (method, TRUE);
1256 g_print ("Could not retrieve method signature for %s\n", desc);
1257 g_free (desc);
1258 fail_count ++;
1259 continue;
1262 if (sig->has_type_parameters)
1263 continue;
1265 count++;
1266 if (verbose) {
1267 char * desc = mono_method_full_name (method, TRUE);
1268 g_print ("Compiling %d %s\n", count, desc);
1269 g_free (desc);
1271 if (mono_use_interpreter) {
1272 mini_get_interp_callbacks ()->create_method_pointer (method, TRUE, error);
1273 // FIXME There are a few failures due to DllNotFoundException related to System.Native
1274 if (verbose && !is_ok (error))
1275 g_print ("Compilation of %s failed\n", mono_method_full_name (method, TRUE));
1276 } else {
1277 cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, args->opts), mono_get_root_domain (), (JitFlags)JIT_FLAG_DISCARD_RESULTS, 0, -1);
1278 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
1279 const char *msg = cfg->exception_message;
1280 if (cfg->exception_type == MONO_EXCEPTION_MONO_ERROR)
1281 msg = mono_error_get_message (cfg->error);
1282 g_print ("Compilation of %s failed with exception '%s':\n", mono_method_full_name (cfg->method, TRUE), msg);
1283 fail_count ++;
1285 mono_destroy_compile (cfg);
1289 if (fail_count)
1290 exit (1);
1293 static void
1294 compile_all_methods_thread_main (gpointer void_args)
1296 CompileAllThreadArgs *args = (CompileAllThreadArgs*)void_args;
1297 guint32 i;
1298 for (i = 0; i < args->recompilation_times; ++i)
1299 compile_all_methods_thread_main_inner (args);
1302 static void
1303 compile_all_methods (MonoAssembly *ass, int verbose, guint32 opts, guint32 recompilation_times)
1305 ERROR_DECL (error);
1306 CompileAllThreadArgs args;
1308 args.ass = ass;
1309 args.verbose = verbose;
1310 args.opts = opts;
1311 args.recompilation_times = recompilation_times;
1314 * Need to create a mono thread since compilation might trigger
1315 * running of managed code.
1317 mono_thread_create_checked (mono_domain_get (), (gpointer)compile_all_methods_thread_main, &args, error);
1318 mono_error_assert_ok (error);
1320 mono_thread_manage_internal ();
1324 * mono_jit_exec:
1325 * \param assembly reference to an assembly
1326 * \param argc argument count
1327 * \param argv argument vector
1328 * Start execution of a program.
1330 int
1331 mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
1333 int rv;
1334 MONO_ENTER_GC_UNSAFE;
1335 rv = mono_jit_exec_internal (domain, assembly, argc, argv);
1336 MONO_EXIT_GC_UNSAFE;
1337 return rv;
1341 mono_jit_exec_internal (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
1343 MONO_REQ_GC_UNSAFE_MODE;
1344 ERROR_DECL (error);
1345 MonoImage *image = mono_assembly_get_image_internal (assembly);
1347 // We need to ensure that any module cctor for this image
1348 // is run *before* we invoke the entry point
1349 // For more information, see https://blogs.msdn.microsoft.com/junfeng/2005/11/19/module-initializer-a-k-a-module-constructor/
1351 // This is required in order for tools like Costura
1352 // (https://github.com/Fody/Costura) to work properly, as they inject
1353 // a module initializer which sets up event handlers (e.g. AssemblyResolve)
1354 // that allow the main method to run properly
1355 if (!mono_runtime_run_module_cctor(image, domain, error)) {
1356 g_print ("Failed to run module constructor due to %s\n", mono_error_get_message (error));
1357 return 1;
1360 MonoMethod *method;
1361 guint32 entry = mono_image_get_entry_point (image);
1363 if (!entry) {
1364 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
1365 /* FIXME: remove this silly requirement. */
1366 mono_environment_exitcode_set (1);
1367 return 1;
1370 method = mono_get_method_checked (image, entry, NULL, NULL, error);
1371 if (method == NULL){
1372 g_print ("The entry point method could not be loaded due to %s\n", mono_error_get_message (error));
1373 mono_error_cleanup (error);
1374 mono_environment_exitcode_set (1);
1375 return 1;
1378 if (mono_llvm_only) {
1379 MonoObject *exc = NULL;
1380 int res;
1382 res = mono_runtime_try_run_main (method, argc, argv, &exc);
1383 if (exc) {
1384 mono_unhandled_exception_internal (exc);
1385 mono_invoke_unhandled_exception_hook (exc);
1386 g_assert_not_reached ();
1388 return res;
1389 } else {
1390 int res = mono_runtime_run_main_checked (method, argc, argv, error);
1391 if (!is_ok (error)) {
1392 MonoException *ex = mono_error_convert_to_exception (error);
1393 if (ex) {
1394 mono_unhandled_exception_internal (&ex->object);
1395 mono_invoke_unhandled_exception_hook (&ex->object);
1396 g_assert_not_reached ();
1399 return res;
1403 typedef struct
1405 MonoDomain *domain;
1406 const char *file;
1407 int argc;
1408 char **argv;
1409 guint32 opts;
1410 char *aot_options;
1411 } MainThreadArgs;
1413 static void main_thread_handler (gpointer user_data)
1415 MainThreadArgs *main_args = (MainThreadArgs *)user_data;
1416 MonoAssembly *assembly;
1418 if (mono_compile_aot) {
1419 int i, res;
1420 gpointer *aot_state = NULL;
1422 /* Treat the other arguments as assemblies to compile too */
1423 for (i = 0; i < main_args->argc; ++i) {
1424 assembly = mono_domain_assembly_open_internal (main_args->domain, mono_domain_default_alc (main_args->domain), main_args->argv [i]);
1425 if (!assembly) {
1426 if (mono_is_problematic_file (main_args->argv [i])) {
1427 fprintf (stderr, "Info: AOT of problematic assembly %s skipped. This is expected.\n", main_args->argv [i]);
1428 continue;
1429 } else {
1430 fprintf (stderr, "Can not open image %s\n", main_args->argv [i]);
1431 exit (1);
1434 /* Check that the assembly loaded matches the filename */
1436 MonoImageOpenStatus status;
1437 MonoImage *img;
1439 img = mono_image_open (main_args->argv [i], &status);
1440 if (img && strcmp (img->name, assembly->image->name)) {
1441 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);
1442 exit (1);
1445 res = mono_compile_assembly (assembly, main_args->opts, main_args->aot_options, &aot_state);
1446 if (res != 0) {
1447 fprintf (stderr, "AOT of image %s failed.\n", main_args->argv [i]);
1448 exit (1);
1451 if (aot_state) {
1452 res = mono_compile_deferred_assemblies (main_args->opts, main_args->aot_options, &aot_state);
1453 if (res != 0) {
1454 fprintf (stderr, "AOT of mode-specific deferred assemblies failed.\n");
1455 exit (1);
1458 } else {
1459 assembly = mono_domain_assembly_open_internal (main_args->domain, mono_domain_default_alc (main_args->domain), main_args->file);
1460 if (!assembly){
1461 fprintf (stderr, "Can not open image %s\n", main_args->file);
1462 exit (1);
1466 * This must be done in a thread managed by mono since it can invoke
1467 * managed code.
1469 if (main_args->opts & MONO_OPT_PRECOMP)
1470 mono_precompile_assemblies ();
1472 mono_jit_exec (main_args->domain, assembly, main_args->argc, main_args->argv);
1476 static int
1477 load_agent (MonoDomain *domain, char *desc)
1479 ERROR_DECL (error);
1480 char* col = strchr (desc, ':');
1481 char *agent, *args;
1482 MonoAssembly *agent_assembly;
1483 MonoImage *image;
1484 MonoMethod *method;
1485 guint32 entry;
1486 MonoArray *main_args;
1487 gpointer pa [1];
1488 MonoImageOpenStatus open_status;
1490 if (col) {
1491 agent = (char *)g_memdup (desc, col - desc + 1);
1492 agent [col - desc] = '\0';
1493 args = col + 1;
1494 } else {
1495 agent = g_strdup (desc);
1496 args = NULL;
1499 MonoAssemblyOpenRequest req;
1500 mono_assembly_request_prepare_open (&req, MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_get_root_domain ()));
1501 agent_assembly = mono_assembly_request_open (agent, &req, &open_status);
1502 if (!agent_assembly) {
1503 fprintf (stderr, "Cannot open agent assembly '%s': %s.\n", agent, mono_image_strerror (open_status));
1504 g_free (agent);
1505 return 2;
1509 * Can't use mono_jit_exec (), as it sets things which might confuse the
1510 * real Main method.
1512 image = mono_assembly_get_image_internal (agent_assembly);
1513 entry = mono_image_get_entry_point (image);
1514 if (!entry) {
1515 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
1516 g_free (agent);
1517 return 1;
1520 method = mono_get_method_checked (image, entry, NULL, NULL, error);
1521 if (method == NULL){
1522 g_print ("The entry point method of assembly '%s' could not be loaded due to %s\n", agent, mono_error_get_message (error));
1523 mono_error_cleanup (error);
1524 g_free (agent);
1525 return 1;
1528 mono_thread_set_main (mono_thread_current ());
1530 if (args) {
1531 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 1, error);
1532 if (main_args) {
1533 MonoString *str = mono_string_new_checked (domain, args, error);
1534 if (str)
1535 mono_array_set_internal (main_args, MonoString*, 0, str);
1537 } else {
1538 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 0, error);
1540 if (!main_args) {
1541 g_print ("Could not allocate array for main args of assembly '%s' due to %s\n", agent, mono_error_get_message (error));
1542 mono_error_cleanup (error);
1543 g_free (agent);
1544 return 1;
1548 pa [0] = main_args;
1549 /* Pass NULL as 'exc' so unhandled exceptions abort the runtime */
1550 mono_runtime_invoke_checked (method, NULL, pa, error);
1551 if (!is_ok (error)) {
1552 g_print ("The entry point method of assembly '%s' could not execute due to %s\n", agent, mono_error_get_message (error));
1553 mono_error_cleanup (error);
1554 g_free (agent);
1555 return 1;
1558 g_free (agent);
1559 return 0;
1562 static void
1563 mini_usage_jitdeveloper (void)
1565 int i;
1567 fprintf (stdout,
1568 "Runtime and JIT debugging options:\n"
1569 " --apply-bindings=FILE Apply assembly bindings from FILE (only for AOT)\n"
1570 " --breakonex Inserts a breakpoint on exceptions\n"
1571 " --break METHOD Inserts a breakpoint at METHOD entry\n"
1572 " --break-at-bb METHOD N Inserts a breakpoint in METHOD at BB N\n"
1573 " --compile METHOD Just compile METHOD in assembly\n"
1574 " --compile-all=N Compiles all the methods in the assembly multiple times (default: 1)\n"
1575 " --ncompile N Number of times to compile METHOD (default: 1)\n"
1576 " --print-vtable Print the vtable of all used classes\n"
1577 " --regression Runs the regression test contained in the assembly\n"
1578 " --single-method=OPTS Runs regressions with only one method optimized with OPTS at any time\n"
1579 " --statfile FILE Sets the stat file to FILE\n"
1580 " --stats Print statistics about the JIT operations\n"
1581 " --inject-async-exc METHOD OFFSET Inject an asynchronous exception at METHOD\n"
1582 " --verify-all Run the verifier on all assemblies and methods\n"
1583 " --full-aot Avoid JITting any code\n"
1584 " --llvmonly Use LLVM compiled code only\n"
1585 " --agent=ASSEMBLY[:ARG] Loads the specific agent assembly and executes its Main method with the given argument before loading the main assembly.\n"
1586 " --no-x86-stack-align Don't align stack on x86\n"
1587 "\n"
1588 "The options supported by MONO_DEBUG can also be passed on the command line.\n"
1589 "\n"
1590 "Other options:\n"
1591 " --graph[=TYPE] METHOD Draws a graph of the specified method:\n");
1593 for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
1594 fprintf (stdout, " %-10s %s\n", graph_names [i].name, graph_names [i].desc);
1598 static void
1599 mini_usage_list_opt (void)
1601 int i;
1603 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i)
1604 fprintf (stdout, " %-10s %s\n", optflag_get_name (i), optflag_get_desc (i));
1607 static void
1608 mini_usage (void)
1610 fprintf (stdout,
1611 "Usage is: mono [options] program [program-options]\n"
1612 "\n"
1613 "Development:\n"
1614 " --aot[=<options>] Compiles the assembly to native code\n"
1615 " --debug[=<options>] Enable debugging support, use --help-debug for details\n"
1616 " --debugger-agent=options Enable the debugger agent\n"
1617 " --profile[=profiler] Runs in profiling mode with the specified profiler module\n"
1618 " --trace[=EXPR] Enable tracing, use --help-trace for details\n"
1619 #ifdef __linux__
1620 " --jitmap Output a jit method map to /tmp/perf-PID.map\n"
1621 #endif
1622 #ifdef ENABLE_JIT_DUMP
1623 " --jitdump Output a jitdump file to /tmp/jit-PID.dump\n"
1624 #endif
1625 " --help-devel Shows more options available to developers\n"
1626 "\n"
1627 "Runtime:\n"
1628 " --config FILE Loads FILE as the Mono config\n"
1629 " --verbose, -v Increases the verbosity level\n"
1630 " --help, -h Show usage information\n"
1631 " --version, -V Show version information\n"
1632 " --version=number Show version number\n"
1633 " --runtime=VERSION Use the VERSION runtime, instead of autodetecting\n"
1634 " --optimize=OPT Turns on or off a specific optimization\n"
1635 " Use --list-opt to get a list of optimizations\n"
1636 " --attach=OPTIONS Pass OPTIONS to the attach agent in the runtime.\n"
1637 " Currently the only supported option is 'disable'.\n"
1638 " --llvm, --nollvm Controls whenever the runtime uses LLVM to compile code.\n"
1639 " --gc=[sgen,boehm] Select SGen or Boehm GC (runs mono or mono-sgen)\n"
1640 #ifdef TARGET_OSX
1641 " --arch=[32,64] Select architecture (runs mono32 or mono64)\n"
1642 #endif
1643 #ifdef HOST_WIN32
1644 " --mixed-mode Enable mixed-mode image support.\n"
1645 #endif
1646 " --handlers Install custom handlers, use --help-handlers for details.\n"
1647 " --aot-path=PATH List of additional directories to search for AOT images.\n"
1650 g_print ("\nOptions:\n");
1651 mono_options_print_usage ();
1654 static void
1655 mini_trace_usage (void)
1657 fprintf (stdout,
1658 "Tracing options:\n"
1659 " --trace[=EXPR] Trace every call, optional EXPR controls the scope\n"
1660 "\n"
1661 "EXPR is composed of:\n"
1662 " all All assemblies\n"
1663 " none No assemblies\n"
1664 " program Entry point assembly\n"
1665 " assembly Specifies an assembly\n"
1666 " wrapper All wrappers bridging native and managed code\n"
1667 " M:Type:Method Specifies a method\n"
1668 " N:Namespace Specifies a namespace\n"
1669 " T:Type Specifies a type\n"
1670 " E:Type Specifies stack traces for an exception type\n"
1671 " EXPR Includes expression\n"
1672 " -EXPR Excludes expression\n"
1673 " EXPR,EXPR Multiple expressions\n"
1674 " disabled Don't print any output until toggled via SIGUSR2\n");
1677 static void
1678 mini_debug_usage (void)
1680 fprintf (stdout,
1681 "Debugging options:\n"
1682 " --debug[=OPTIONS] Enable debugging support, optional OPTIONS is a comma\n"
1683 " separated list of options\n"
1684 "\n"
1685 "OPTIONS is composed of:\n"
1686 " casts Enable more detailed InvalidCastException messages.\n"
1687 " mdb-optimizations Disable some JIT optimizations which are normally\n"
1688 " disabled when running inside the debugger.\n"
1689 " This is useful if you plan to attach to the running\n"
1690 " process with the debugger.\n");
1693 #if defined(MONO_ARCH_ARCHITECTURE)
1694 /* Redefine MONO_ARCHITECTURE to include more information */
1695 #undef MONO_ARCHITECTURE
1696 #define MONO_ARCHITECTURE MONO_ARCH_ARCHITECTURE
1697 #endif
1699 static char *
1700 mono_get_version_info (void)
1702 GString *output;
1703 output = g_string_new ("");
1705 #ifdef MONO_KEYWORD_THREAD
1706 g_string_append_printf (output, "\tTLS: __thread\n");
1707 #else
1708 g_string_append_printf (output, "\tTLS: \n");
1709 #endif /* MONO_KEYWORD_THREAD */
1711 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
1712 g_string_append_printf (output, "\tSIGSEGV: altstack\n");
1713 #else
1714 g_string_append_printf (output, "\tSIGSEGV: normal\n");
1715 #endif
1717 #ifdef HAVE_EPOLL
1718 g_string_append_printf (output, "\tNotifications: epoll\n");
1719 #elif defined(HAVE_KQUEUE)
1720 g_string_append_printf (output, "\tNotification: kqueue\n");
1721 #else
1722 g_string_append_printf (output, "\tNotification: Thread + polling\n");
1723 #endif
1725 g_string_append_printf (output, "\tArchitecture: %s\n", MONO_ARCHITECTURE);
1726 g_string_append_printf (output, "\tDisabled: %s\n", DISABLED_FEATURES);
1728 g_string_append_printf (output, "\tMisc: ");
1729 #ifdef MONO_SMALL_CONFIG
1730 g_string_append_printf (output, "smallconfig ");
1731 #endif
1733 #ifdef MONO_BIG_ARRAYS
1734 g_string_append_printf (output, "bigarrays ");
1735 #endif
1737 #if !defined(DISABLE_SDB)
1738 g_string_append_printf (output, "softdebug ");
1739 #endif
1740 g_string_append_printf (output, "\n");
1742 #ifndef DISABLE_INTERPRETER
1743 g_string_append_printf (output, "\tInterpreter: yes\n");
1744 #else
1745 g_string_append_printf (output, "\tInterpreter: no\n");
1746 #endif
1748 #ifdef MONO_ARCH_LLVM_SUPPORTED
1749 #ifdef ENABLE_LLVM
1750 g_string_append_printf (output, "\tLLVM: yes(%d)\n", LLVM_API_VERSION);
1751 #else
1752 g_string_append_printf (output, "\tLLVM: supported, not enabled.\n");
1753 #endif
1754 #endif
1756 mono_threads_suspend_policy_init ();
1757 g_string_append_printf (output, "\tSuspend: %s\n", mono_threads_suspend_policy_name (mono_threads_suspend_policy ()));
1759 return g_string_free (output, FALSE);
1762 #ifndef MONO_ARCH_AOT_SUPPORTED
1763 #define error_if_aot_unsupported() do {fprintf (stderr, "AOT compilation is not supported on this platform.\n"); exit (1);} while (0)
1764 #else
1765 #define error_if_aot_unsupported()
1766 #endif
1768 static gboolean enable_debugging;
1770 static void
1771 enable_runtime_stats (void)
1773 mono_counters_enable (-1);
1774 mono_atomic_store_bool (&mono_stats.enabled, TRUE);
1775 mono_atomic_store_bool (&mono_jit_stats.enabled, TRUE);
1778 static MonoMethodDesc *
1779 parse_qualified_method_name (char *method_name)
1781 if (strlen (method_name) == 0) {
1782 g_printerr ("Couldn't parse empty method name.");
1783 exit (1);
1785 MonoMethodDesc *result = mono_method_desc_new (method_name, TRUE);
1786 if (!result) {
1787 g_printerr ("Couldn't parse method name: %s\n", method_name);
1788 exit (1);
1790 return result;
1794 * mono_jit_parse_options:
1796 * Process the command line options in \p argv as done by the runtime executable.
1797 * This should be called before \c mono_jit_init.
1799 void
1800 mono_jit_parse_options (int argc, char * argv[])
1802 int i;
1803 char *trace_options = NULL;
1804 int mini_verbose_level = 0;
1805 guint32 opt;
1808 * Some options have no effect here, since they influence the behavior of
1809 * mono_main ().
1812 opt = mono_parse_default_optimizations (NULL);
1814 /* FIXME: Avoid code duplication */
1815 for (i = 0; i < argc; ++i) {
1816 if (argv [i] [0] != '-')
1817 break;
1818 if (strncmp (argv [i], "--debugger-agent=", 17) == 0) {
1819 MonoDebugOptions *opt = mini_get_debug_options ();
1821 sdb_options = g_strdup (argv [i] + 17);
1822 opt->mdb_optimizations = TRUE;
1823 enable_debugging = TRUE;
1824 } else if (!strcmp (argv [i], "--soft-breakpoints")) {
1825 MonoDebugOptions *opt = mini_get_debug_options ();
1827 opt->soft_breakpoints = TRUE;
1828 opt->explicit_null_checks = TRUE;
1829 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
1830 opt = parse_optimizations (opt, argv [i] + 11, TRUE);
1831 mono_set_optimizations (opt);
1832 } else if (strncmp (argv [i], "-O=", 3) == 0) {
1833 opt = parse_optimizations (opt, argv [i] + 3, TRUE);
1834 mono_set_optimizations (opt);
1835 } else if (strcmp (argv [i], "--trace") == 0) {
1836 trace_options = (char*)"";
1837 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
1838 trace_options = &argv [i][8];
1839 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
1840 mini_verbose_level++;
1841 } else if (strcmp (argv [i], "--breakonex") == 0) {
1842 MonoDebugOptions *opt = mini_get_debug_options ();
1844 opt->break_on_exc = TRUE;
1845 } else if (strcmp (argv [i], "--stats") == 0) {
1846 enable_runtime_stats ();
1847 } else if (strncmp (argv [i], "--stats=", 8) == 0) {
1848 enable_runtime_stats ();
1849 if (mono_stats_method_desc)
1850 g_free (mono_stats_method_desc);
1851 mono_stats_method_desc = parse_qualified_method_name (argv [i] + 8);
1852 } else if (strcmp (argv [i], "--break") == 0) {
1853 if (i+1 >= argc){
1854 fprintf (stderr, "Missing method name in --break command line option\n");
1855 exit (1);
1858 if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
1859 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
1860 } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
1861 mono_gc_params_set (argv[i] + 12);
1862 } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
1863 mono_gc_debug_set (argv[i] + 11);
1864 } else if (strcmp (argv [i], "--llvm") == 0) {
1865 #ifndef MONO_ARCH_LLVM_SUPPORTED
1866 fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
1867 #elif !defined(ENABLE_LLVM)
1868 fprintf (stderr, "Mono Warning: --llvm not enabled in this runtime.\n");
1869 #else
1870 mono_use_llvm = TRUE;
1871 #endif
1872 } else if (strcmp (argv [i], "--profile") == 0) {
1873 mini_add_profiler_argument (NULL);
1874 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
1875 mini_add_profiler_argument (argv [i] + 10);
1876 } else if (argv [i][0] == '-' && argv [i][1] == '-' && mini_parse_debug_option (argv [i] + 2)) {
1877 } else {
1878 fprintf (stderr, "Unsupported command line option: '%s'\n", argv [i]);
1879 exit (1);
1883 if (trace_options != NULL) {
1885 * Need to call this before mini_init () so we can trace methods
1886 * compiled there too.
1888 mono_jit_trace_calls = mono_trace_set_options (trace_options);
1889 if (mono_jit_trace_calls == NULL)
1890 exit (1);
1893 if (mini_verbose_level)
1894 mono_set_verbose_level (mini_verbose_level);
1897 static void
1898 mono_set_use_smp (int use_smp)
1900 #if HAVE_SCHED_SETAFFINITY
1901 if (!use_smp) {
1902 unsigned long proc_mask = 1;
1903 #ifdef GLIBC_BEFORE_2_3_4_SCHED_SETAFFINITY
1904 sched_setaffinity (getpid(), (gpointer)&proc_mask);
1905 #else
1906 sched_setaffinity (getpid(), sizeof (unsigned long), (const cpu_set_t *)&proc_mask);
1907 #endif
1909 #endif
1912 static void
1913 switch_gc (char* argv[], const char* target_gc)
1915 GString *path;
1917 if (!strcmp (mono_gc_get_gc_name (), target_gc)) {
1918 return;
1921 path = g_string_new (argv [0]);
1923 /*Running mono without any argument*/
1924 if (strstr (argv [0], "-sgen"))
1925 g_string_truncate (path, path->len - 5);
1926 else if (strstr (argv [0], "-boehm"))
1927 g_string_truncate (path, path->len - 6);
1929 g_string_append_c (path, '-');
1930 g_string_append (path, target_gc);
1932 #ifdef HAVE_EXECVP
1933 execvp (path->str, argv);
1934 fprintf (stderr, "Error: Failed to switch to %s gc. mono-%s is not installed.\n", target_gc, target_gc);
1935 #else
1936 fprintf (stderr, "Error: --gc=<NAME> option not supported on this platform.\n");
1937 #endif
1940 #ifdef TARGET_OSX
1943 * tries to increase the minimum number of files, if the number is below 1024
1945 static void
1946 darwin_change_default_file_handles ()
1948 struct rlimit limit;
1950 if (getrlimit (RLIMIT_NOFILE, &limit) == 0){
1951 if (limit.rlim_cur < 1024){
1952 limit.rlim_cur = MAX(1024,limit.rlim_cur);
1953 setrlimit (RLIMIT_NOFILE, &limit);
1958 static void
1959 switch_arch (char* argv[], const char* target_arch)
1961 GString *path;
1962 gsize arch_offset;
1964 if ((strcmp (target_arch, "32") == 0 && strcmp (MONO_ARCHITECTURE, "x86") == 0) ||
1965 (strcmp (target_arch, "64") == 0 && strcmp (MONO_ARCHITECTURE, "amd64") == 0)) {
1966 return; /* matching arch loaded */
1969 path = g_string_new (argv [0]);
1970 arch_offset = path->len -2; /* last two characters */
1972 /* Remove arch suffix if present */
1973 if (strstr (&path->str[arch_offset], "32") || strstr (&path->str[arch_offset], "64")) {
1974 g_string_truncate (path, arch_offset);
1977 g_string_append (path, target_arch);
1979 if (execvp (path->str, argv) < 0) {
1980 fprintf (stderr, "Error: --arch=%s Failed to switch to '%s'.\n", target_arch, path->str);
1981 exit (1);
1985 #endif
1987 #define MONO_HANDLERS_ARGUMENT "--handlers="
1988 #define MONO_HANDLERS_ARGUMENT_LEN G_N_ELEMENTS(MONO_HANDLERS_ARGUMENT)-1
1990 static void
1991 apply_root_domain_configuration_file_bindings (MonoDomain *domain, char *root_domain_configuration_file)
1993 g_assert (domain->setup == NULL || domain->setup->configuration_file == NULL);
1994 g_assert (!domain->assembly_bindings_parsed);
1996 mono_domain_parse_assembly_bindings (domain, 0, 0, root_domain_configuration_file);
1999 static void
2000 mono_check_interp_supported (void)
2002 #ifdef MONO_CROSS_COMPILE
2003 g_error ("--interpreter on cross-compile runtimes not supported\n");
2004 #endif
2006 #ifndef MONO_ARCH_INTERPRETER_SUPPORTED
2007 g_error ("--interpreter not supported on this architecture.\n");
2008 #endif
2011 static int
2012 mono_exec_regression_internal (int verbose_level, int count, char *images [], gboolean single_method)
2014 mono_do_single_method_regression = single_method;
2015 if (mono_use_interpreter) {
2016 if (mono_interp_regression_list (verbose_level, count, images)) {
2017 g_print ("Regression ERRORS!\n");
2018 return 1;
2020 return 0;
2022 if (mini_regression_list (verbose_level, count, images)) {
2023 g_print ("Regression ERRORS!\n");
2024 return 1;
2026 return 0;
2031 * Returns TRUE for success, FALSE for failure.
2033 gboolean
2034 mono_regression_test_step (int verbose_level, const char *image, const char *method_name)
2036 if (method_name) {
2037 //TODO
2038 } else {
2039 do_regression_retries = TRUE;
2042 char *images[] = {
2043 (char*)image,
2044 NULL
2047 return mono_exec_regression_internal (verbose_level, 1, images, FALSE) == 0;
2050 #ifdef ENABLE_ICALL_SYMBOL_MAP
2051 /* Print the icall table as JSON */
2052 static void
2053 print_icall_table (void)
2055 // We emit some dummy values to make the code simpler
2057 printf ("[\n{ \"klass\": \"\", \"icalls\": [");
2058 #define NOHANDLES(inner) inner
2059 #define HANDLES(id, name, func, ...) printf ("\t,{ \"name\": \"%s\", \"func\": \"%s_raw\", \"handles\": true }\n", name, #func);
2060 #define HANDLES_REUSE_WRAPPER HANDLES
2061 #define MONO_HANDLE_REGISTER_ICALL(...) /* nothing */
2062 #define ICALL_TYPE(id,name,first) printf ("]},\n { \"klass\":\"%s\", \"icalls\": [{} ", name);
2063 #define ICALL(id,name,func) printf ("\t,{ \"name\": \"%s\", \"func\": \"%s\", \"handles\": false }\n", name, #func);
2064 #include <mono/metadata/icall-def.h>
2066 printf ("]}\n]\n");
2068 #endif
2071 * mono_main:
2072 * \param argc number of arguments in the argv array
2073 * \param argv array of strings containing the startup arguments
2074 * Launches the Mono JIT engine and parses all the command line options
2075 * in the same way that the mono command line VM would.
2078 mono_main (int argc, char* argv[])
2080 MainThreadArgs main_args;
2081 MonoAssembly *assembly;
2082 MonoMethodDesc *desc;
2083 MonoMethod *method;
2084 MonoDomain *domain;
2085 MonoImageOpenStatus open_status;
2086 const char* aname, *mname = NULL;
2087 char *config_file = NULL;
2088 int i, count = 1;
2089 guint32 opt, action = DO_EXEC, recompilation_times = 1;
2090 MonoGraphOptions mono_graph_options = (MonoGraphOptions)0;
2091 int mini_verbose_level = 0;
2092 char *trace_options = NULL;
2093 char *aot_options = NULL;
2094 char *forced_version = NULL;
2095 GPtrArray *agents = NULL;
2096 char *attach_options = NULL;
2097 char *extra_bindings_config_file = NULL;
2098 #ifdef MONO_JIT_INFO_TABLE_TEST
2099 int test_jit_info_table = FALSE;
2100 #endif
2101 #ifdef HOST_WIN32
2102 int mixed_mode = FALSE;
2103 #endif
2104 ERROR_DECL (error);
2106 #ifdef MOONLIGHT
2107 #ifndef HOST_WIN32
2108 /* stdout defaults to block buffering if it's not writing to a terminal, which
2109 * happens with our test harness: we redirect stdout to capture it. Force line
2110 * buffering in all cases. */
2111 setlinebuf (stdout);
2112 #endif
2113 #endif
2115 setlocale (LC_ALL, "");
2117 #if TARGET_OSX
2118 darwin_change_default_file_handles ();
2119 #endif
2121 if (g_hasenv ("MONO_NO_SMP"))
2122 mono_set_use_smp (FALSE);
2124 #ifdef MONO_JEMALLOC_ENABLED
2126 gboolean use_jemalloc = FALSE;
2127 #ifdef MONO_JEMALLOC_DEFAULT
2128 use_jemalloc = TRUE;
2129 #endif
2130 if (!use_jemalloc)
2131 use_jemalloc = g_hasenv ("MONO_USE_JEMALLOC");
2133 if (use_jemalloc)
2134 mono_init_jemalloc ();
2136 #endif
2138 g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
2139 g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
2141 opt = mono_parse_default_optimizations (NULL);
2144 mono_options_parse_options ((const char**)argv + 1, argc - 1, &argc, error);
2145 argc ++;
2146 if (!is_ok (error)) {
2147 g_printerr ("%s", mono_error_get_message (error));
2148 mono_error_cleanup (error);
2149 return 1;
2152 for (i = 1; i < argc; ++i) {
2153 if (argv [i] [0] != '-')
2154 break;
2155 if (strcmp (argv [i], "--regression") == 0) {
2156 action = DO_REGRESSION;
2157 } else if (strncmp (argv [i], "--single-method=", 16) == 0) {
2158 char *full_opts = g_strdup_printf ("-all,%s", argv [i] + 16);
2159 action = DO_SINGLE_METHOD_REGRESSION;
2160 mono_single_method_regression_opt = parse_optimizations (opt, full_opts, TRUE);
2161 g_free (full_opts);
2162 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
2163 mini_verbose_level++;
2164 } else if (strcmp (argv [i], "--version=number") == 0) {
2165 g_print ("%s\n", VERSION);
2166 return 0;
2167 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
2168 char *build = mono_get_runtime_build_info ();
2169 char *gc_descr;
2171 g_print ("Mono JIT compiler version %s\nCopyright (C) Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com\n", build);
2172 g_free (build);
2173 char *info = mono_get_version_info ();
2174 g_print (info);
2175 g_free (info);
2177 gc_descr = mono_gc_get_description ();
2178 g_print ("\tGC: %s\n", gc_descr);
2179 g_free (gc_descr);
2180 return 0;
2181 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
2182 mini_usage ();
2183 return 0;
2184 } else if (strcmp (argv [i], "--help-trace") == 0){
2185 mini_trace_usage ();
2186 return 0;
2187 } else if (strcmp (argv [i], "--help-devel") == 0){
2188 mini_usage_jitdeveloper ();
2189 return 0;
2190 } else if (strcmp (argv [i], "--help-debug") == 0){
2191 mini_debug_usage ();
2192 return 0;
2193 } else if (strcmp (argv [i], "--list-opt") == 0){
2194 mini_usage_list_opt ();
2195 return 0;
2196 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
2197 if (i + 1 >= argc){
2198 fprintf (stderr, "error: --statfile requires a filename argument\n");
2199 return 1;
2201 mini_stats_fd = fopen (argv [++i], "w+");
2202 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
2203 opt = parse_optimizations (opt, argv [i] + 11, TRUE);
2204 } else if (strncmp (argv [i], "-O=", 3) == 0) {
2205 opt = parse_optimizations (opt, argv [i] + 3, TRUE);
2206 } else if (strncmp (argv [i], "--bisect=", 9) == 0) {
2207 char *param = argv [i] + 9;
2208 char *sep = strchr (param, ':');
2209 if (!sep) {
2210 fprintf (stderr, "Error: --bisect requires OPT:FILENAME\n");
2211 return 1;
2213 char *opt_string = g_strndup (param, sep - param);
2214 guint32 opt = parse_optimizations (0, opt_string, FALSE);
2215 g_free (opt_string);
2216 mono_set_bisect_methods (opt, sep + 1);
2217 } else if (strcmp (argv [i], "--gc=sgen") == 0) {
2218 switch_gc (argv, "sgen");
2219 } else if (strcmp (argv [i], "--gc=boehm") == 0) {
2220 switch_gc (argv, "boehm");
2221 } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
2222 mono_gc_params_set (argv[i] + 12);
2223 } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
2224 mono_gc_debug_set (argv[i] + 11);
2226 #ifdef TARGET_OSX
2227 else if (strcmp (argv [i], "--arch=32") == 0) {
2228 switch_arch (argv, "32");
2229 } else if (strcmp (argv [i], "--arch=64") == 0) {
2230 switch_arch (argv, "64");
2232 #endif
2233 else if (strcmp (argv [i], "--config") == 0) {
2234 if (i +1 >= argc){
2235 fprintf (stderr, "error: --config requires a filename argument\n");
2236 return 1;
2238 config_file = argv [++i];
2239 #ifdef HOST_WIN32
2240 } else if (strcmp (argv [i], "--mixed-mode") == 0) {
2241 mixed_mode = TRUE;
2242 #endif
2243 } else if (strcmp (argv [i], "--ncompile") == 0) {
2244 if (i + 1 >= argc){
2245 fprintf (stderr, "error: --ncompile requires an argument\n");
2246 return 1;
2248 count = atoi (argv [++i]);
2249 action = DO_BENCH;
2250 } else if (strcmp (argv [i], "--trace") == 0) {
2251 trace_options = (char*)"";
2252 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
2253 trace_options = &argv [i][8];
2254 } else if (strcmp (argv [i], "--breakonex") == 0) {
2255 MonoDebugOptions *opt = mini_get_debug_options ();
2257 opt->break_on_exc = TRUE;
2258 } else if (strcmp (argv [i], "--break") == 0) {
2259 if (i+1 >= argc){
2260 fprintf (stderr, "Missing method name in --break command line option\n");
2261 return 1;
2264 if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
2265 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
2266 } else if (strcmp (argv [i], "--break-at-bb") == 0) {
2267 if (i + 2 >= argc) {
2268 fprintf (stderr, "Missing method name or bb num in --break-at-bb command line option.");
2269 return 1;
2271 mono_break_at_bb_method = mono_method_desc_new (argv [++i], TRUE);
2272 if (mono_break_at_bb_method == NULL) {
2273 fprintf (stderr, "Method name is in a bad format in --break-at-bb command line option.");
2274 return 1;
2276 mono_break_at_bb_bb_num = atoi (argv [++i]);
2277 } else if (strcmp (argv [i], "--inject-async-exc") == 0) {
2278 if (i + 2 >= argc) {
2279 fprintf (stderr, "Missing method name or position in --inject-async-exc command line option\n");
2280 return 1;
2282 mono_inject_async_exc_method = mono_method_desc_new (argv [++i], TRUE);
2283 if (mono_inject_async_exc_method == NULL) {
2284 fprintf (stderr, "Method name is in a bad format in --inject-async-exc command line option\n");
2285 return 1;
2287 mono_inject_async_exc_pos = atoi (argv [++i]);
2288 } else if (strcmp (argv [i], "--verify-all") == 0) {
2289 mono_verifier_enable_verify_all ();
2290 } else if (strcmp (argv [i], "--full-aot") == 0) {
2291 mono_jit_set_aot_mode (MONO_AOT_MODE_FULL);
2292 } else if (strcmp (argv [i], "--llvmonly") == 0) {
2293 mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY);
2294 } else if (strcmp (argv [i], "--hybrid-aot") == 0) {
2295 mono_jit_set_aot_mode (MONO_AOT_MODE_HYBRID);
2296 } else if (strcmp (argv [i], "--full-aot-interp") == 0) {
2297 mono_jit_set_aot_mode (MONO_AOT_MODE_INTERP);
2298 } else if (strcmp (argv [i], "--llvmonly-interp") == 0) {
2299 mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY_INTERP);
2300 } else if (strcmp (argv [i], "--print-vtable") == 0) {
2301 mono_print_vtable = TRUE;
2302 } else if (strcmp (argv [i], "--stats") == 0) {
2303 enable_runtime_stats ();
2304 } else if (strncmp (argv [i], "--stats=", 8) == 0) {
2305 enable_runtime_stats ();
2306 if (mono_stats_method_desc)
2307 g_free (mono_stats_method_desc);
2308 mono_stats_method_desc = parse_qualified_method_name (argv [i] + 8);
2309 #ifndef DISABLE_AOT
2310 } else if (strcmp (argv [i], "--aot") == 0) {
2311 error_if_aot_unsupported ();
2312 mono_compile_aot = TRUE;
2313 } else if (strncmp (argv [i], "--aot=", 6) == 0) {
2314 error_if_aot_unsupported ();
2315 mono_compile_aot = TRUE;
2316 if (aot_options) {
2317 char *tmp = g_strdup_printf ("%s,%s", aot_options, &argv [i][6]);
2318 g_free (aot_options);
2319 aot_options = tmp;
2320 } else {
2321 aot_options = g_strdup (&argv [i][6]);
2323 #endif
2324 } else if (strncmp (argv [i], "--apply-bindings=", 17) == 0) {
2325 extra_bindings_config_file = &argv[i][17];
2326 } else if (strncmp (argv [i], "--aot-path=", 11) == 0) {
2327 char **splitted;
2329 splitted = g_strsplit (argv [i] + 11, G_SEARCHPATH_SEPARATOR_S, 1000);
2330 while (*splitted) {
2331 char *tmp = *splitted;
2332 mono_aot_paths = g_list_append (mono_aot_paths, g_strdup (tmp));
2333 g_free (tmp);
2334 splitted++;
2336 } else if (strncmp (argv [i], "--compile-all=", 14) == 0) {
2337 action = DO_COMPILE;
2338 recompilation_times = atoi (argv [i] + 14);
2339 } else if (strcmp (argv [i], "--compile-all") == 0) {
2340 action = DO_COMPILE;
2341 } else if (strncmp (argv [i], "--runtime=", 10) == 0) {
2342 forced_version = &argv [i][10];
2343 } else if (strcmp (argv [i], "--jitmap") == 0) {
2344 mono_enable_jit_map ();
2345 #ifdef ENABLE_JIT_DUMP
2346 } else if (strcmp (argv [i], "--jitdump") == 0) {
2347 mono_enable_jit_dump ();
2348 #endif
2349 } else if (strcmp (argv [i], "--profile") == 0) {
2350 mini_add_profiler_argument (NULL);
2351 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
2352 mini_add_profiler_argument (argv [i] + 10);
2353 } else if (strncmp (argv [i], "--agent=", 8) == 0) {
2354 if (agents == NULL)
2355 agents = g_ptr_array_new ();
2356 g_ptr_array_add (agents, argv [i] + 8);
2357 } else if (strncmp (argv [i], "--attach=", 9) == 0) {
2358 attach_options = argv [i] + 9;
2359 } else if (strcmp (argv [i], "--compile") == 0) {
2360 if (i + 1 >= argc){
2361 fprintf (stderr, "error: --compile option requires a method name argument\n");
2362 return 1;
2365 mname = argv [++i];
2366 action = DO_BENCH;
2367 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
2368 if (i + 1 >= argc){
2369 fprintf (stderr, "error: --graph option requires a method name argument\n");
2370 return 1;
2373 mono_graph_options = mono_parse_graph_options (argv [i] + 8);
2374 mname = argv [++i];
2375 action = DO_DRAW;
2376 } else if (strcmp (argv [i], "--graph") == 0) {
2377 if (i + 1 >= argc){
2378 fprintf (stderr, "error: --graph option requires a method name argument\n");
2379 return 1;
2382 mname = argv [++i];
2383 mono_graph_options = MONO_GRAPH_CFG;
2384 action = DO_DRAW;
2385 } else if (strcmp (argv [i], "--debug") == 0) {
2386 enable_debugging = TRUE;
2387 } else if (strncmp (argv [i], "--debug=", 8) == 0) {
2388 enable_debugging = TRUE;
2389 if (!parse_debug_options (argv [i] + 8))
2390 return 1;
2391 } else if (strncmp (argv [i], "--debugger-agent=", 17) == 0) {
2392 MonoDebugOptions *opt = mini_get_debug_options ();
2394 sdb_options = g_strdup (argv [i] + 17);
2395 opt->mdb_optimizations = TRUE;
2396 enable_debugging = TRUE;
2397 } else if (strcmp (argv [i], "--security") == 0) {
2398 #ifndef DISABLE_SECURITY
2399 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2400 #else
2401 fprintf (stderr, "error: --security: not compiled with security manager support");
2402 return 1;
2403 #endif
2404 } else if (strncmp (argv [i], "--security=", 11) == 0) {
2405 /* Note: validil, and verifiable need to be
2406 accepted even if DISABLE_SECURITY is defined. */
2408 if (strcmp (argv [i] + 11, "core-clr") == 0) {
2409 #ifndef DISABLE_SECURITY
2410 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2411 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
2412 #else
2413 fprintf (stderr, "error: --security: not compiled with CoreCLR support");
2414 return 1;
2415 #endif
2416 } else if (strcmp (argv [i] + 11, "core-clr-test") == 0) {
2417 #ifndef DISABLE_SECURITY
2418 /* fixme should we enable verifiable code here?*/
2419 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
2420 mono_security_core_clr_test = TRUE;
2421 #else
2422 fprintf (stderr, "error: --security: not compiled with CoreCLR support");
2423 return 1;
2424 #endif
2425 } else if (strcmp (argv [i] + 11, "cas") == 0) {
2426 #ifndef DISABLE_SECURITY
2427 fprintf (stderr, "warning: --security=cas not supported.");
2428 #else
2429 fprintf (stderr, "error: --security: not compiled with CAS support");
2430 return 1;
2431 #endif
2432 } else if (strcmp (argv [i] + 11, "validil") == 0) {
2433 mono_verifier_set_mode (MONO_VERIFIER_MODE_VALID);
2434 } else if (strcmp (argv [i] + 11, "verifiable") == 0) {
2435 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2436 } else {
2437 fprintf (stderr, "error: --security= option has invalid argument (cas, core-clr, verifiable or validil)\n");
2438 return 1;
2440 } else if (strcmp (argv [i], "--desktop") == 0) {
2441 mono_gc_set_desktop_mode ();
2442 /* Put more desktop-specific optimizations here */
2443 } else if (strcmp (argv [i], "--server") == 0){
2444 mono_config_set_server_mode (TRUE);
2445 /* Put more server-specific optimizations here */
2446 } else if (strcmp (argv [i], "--inside-mdb") == 0) {
2447 action = DO_DEBUGGER;
2448 } else if (strncmp (argv [i], "--wapi=", 7) == 0) {
2449 fprintf (stderr, "--wapi= option no longer supported\n.");
2450 return 1;
2451 } else if (strcmp (argv [i], "--no-x86-stack-align") == 0) {
2452 mono_do_x86_stack_align = FALSE;
2453 #ifdef MONO_JIT_INFO_TABLE_TEST
2454 } else if (strcmp (argv [i], "--test-jit-info-table") == 0) {
2455 test_jit_info_table = TRUE;
2456 #endif
2457 } else if (strcmp (argv [i], "--llvm") == 0) {
2458 #ifndef MONO_ARCH_LLVM_SUPPORTED
2459 fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
2460 #elif !defined(ENABLE_LLVM)
2461 fprintf (stderr, "Mono Warning: --llvm not enabled in this runtime.\n");
2462 #else
2463 mono_use_llvm = TRUE;
2464 #endif
2465 } else if (strcmp (argv [i], "--nollvm") == 0){
2466 mono_use_llvm = FALSE;
2467 } else if (strcmp (argv [i], "--ffast-math") == 0){
2468 mono_use_fast_math = TRUE;
2469 } else if ((strcmp (argv [i], "--interpreter") == 0) || !strcmp (argv [i], "--interp")) {
2470 mono_runtime_set_execution_mode (MONO_EE_MODE_INTERP);
2471 } else if (strncmp (argv [i], "--interp=", 9) == 0) {
2472 mono_runtime_set_execution_mode_full (MONO_EE_MODE_INTERP, FALSE);
2473 mono_interp_opts_string = argv [i] + 9;
2474 } else if (strcmp (argv [i], "--print-icall-table") == 0) {
2475 #ifdef ENABLE_ICALL_SYMBOL_MAP
2476 print_icall_table ();
2477 exit (0);
2478 #else
2479 fprintf (stderr, "--print-icall-table requires a runtime configured with the --enable-icall-symbol-map option.\n");
2480 exit (1);
2481 #endif
2482 } else if (strncmp (argv [i], "--assembly-loader=", strlen("--assembly-loader=")) == 0) {
2483 gchar *arg = argv [i] + strlen ("--assembly-loader=");
2484 if (strcmp (arg, "strict") == 0)
2485 mono_loader_set_strict_assembly_name_check (TRUE);
2486 else if (strcmp (arg, "legacy") == 0)
2487 mono_loader_set_strict_assembly_name_check (FALSE);
2488 else
2489 fprintf (stderr, "Warning: unknown argument to --assembly-loader. Should be \"strict\" or \"legacy\"\n");
2490 } else if (strncmp (argv [i], MONO_HANDLERS_ARGUMENT, MONO_HANDLERS_ARGUMENT_LEN) == 0) {
2491 //Install specific custom handlers.
2492 if (!mono_runtime_install_custom_handlers (argv[i] + MONO_HANDLERS_ARGUMENT_LEN)) {
2493 fprintf (stderr, "error: " MONO_HANDLERS_ARGUMENT ", one or more unknown handlers: '%s'\n", argv [i]);
2494 return 1;
2496 } else if (strcmp (argv [i], "--help-handlers") == 0) {
2497 mono_runtime_install_custom_handlers_usage ();
2498 return 0;
2499 } else if (strncmp (argv [i], "--response=", 11) == 0){
2500 gchar *response_content;
2501 gchar *response_options;
2502 gsize response_content_len;
2504 if (!g_file_get_contents (&argv[i][11], &response_content, &response_content_len, NULL)){
2505 fprintf (stderr, "The specified response file can not be read\n");
2506 exit (1);
2509 response_options = response_content;
2511 // Check for UTF8 BOM in file and remove if found.
2512 if (response_content_len >= 3 && response_content [0] == '\xef' && response_content [1] == '\xbb' && response_content [2] == '\xbf') {
2513 response_content_len -= 3;
2514 response_options += 3;
2517 if (response_content_len == 0) {
2518 fprintf (stderr, "The specified response file is empty\n");
2519 exit (1);
2522 mono_parse_response_options (response_options, &argc, &argv, FALSE);
2523 g_free (response_content);
2524 } else if (argv [i][0] == '-' && argv [i][1] == '-' && mini_parse_debug_option (argv [i] + 2)) {
2525 } else if (strcmp (argv [i], "--use-map-jit") == 0){
2526 mono_setmmapjit (TRUE);
2527 } else {
2528 fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
2529 return 1;
2533 #if defined(DISABLE_HW_TRAPS) || defined(MONO_ARCH_DISABLE_HW_TRAPS)
2534 // Signal handlers not available
2536 MonoDebugOptions *opt = mini_get_debug_options ();
2537 opt->explicit_null_checks = TRUE;
2539 #endif
2541 if (!argv [i]) {
2542 mini_usage ();
2543 return 1;
2547 * XXX: verify if other OSes need it; many platforms seem to have it so that
2548 * mono_w32process_get_path -> mono_w32process_get_name, and the name is not
2549 * necessarily a path instead of just the program name
2551 #if defined (_AIX)
2553 * mono_w32process_get_path on these can only return a name, not a path;
2554 * which may not be good for us if the mono command name isn't on $PATH,
2555 * like in CI scenarios. chances are argv based is fine if we inherited
2556 * the environment variables.
2558 mono_w32process_set_cli_launcher (argv [0]);
2559 #elif !defined(HOST_WIN32) && defined(HAVE_UNISTD_H)
2561 * If we are not embedded, use the mono runtime executable to run managed exe's.
2564 char *runtime_path;
2566 runtime_path = mono_w32process_get_path (getpid ());
2567 if (runtime_path) {
2568 mono_w32process_set_cli_launcher (runtime_path);
2569 g_free (runtime_path);
2572 #endif
2574 if (g_hasenv ("MONO_XDEBUG"))
2575 enable_debugging = TRUE;
2577 #ifdef MONO_CROSS_COMPILE
2578 if (!mono_compile_aot) {
2579 fprintf (stderr, "This mono runtime is compiled for cross-compiling. Only the --aot option is supported.\n");
2580 exit (1);
2582 #if TARGET_SIZEOF_VOID_P == 4 && (defined(TARGET_ARM64) || defined(TARGET_AMD64)) && !defined(MONO_ARCH_ILP32)
2583 fprintf (stderr, "Can't cross-compile on 32-bit platforms to 64-bit architecture.\n");
2584 exit (1);
2585 #endif
2586 #endif
2588 if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
2589 g_set_prgname (argv[i]);
2592 mono_counters_init ();
2594 #ifndef HOST_WIN32
2595 mono_w32handle_init ();
2596 #endif
2598 /* Set rootdir before loading config */
2599 mono_set_rootdir ();
2601 mono_attach_parse_options (attach_options);
2603 if (trace_options != NULL){
2605 * Need to call this before mini_init () so we can trace methods
2606 * compiled there too.
2608 mono_jit_trace_calls = mono_trace_set_options (trace_options);
2609 if (mono_jit_trace_calls == NULL)
2610 exit (1);
2613 #ifdef DISABLE_JIT
2614 if (!mono_aot_only && !mono_use_interpreter) {
2615 fprintf (stderr, "This runtime has been configured with --enable-minimal=jit, so the --full-aot command line option is required.\n");
2616 exit (1);
2618 #endif
2620 if (action == DO_DEBUGGER) {
2621 enable_debugging = TRUE;
2622 g_print ("The Mono Debugger is no longer supported.\n");
2623 return 1;
2624 } else if (enable_debugging)
2625 mono_debug_init (MONO_DEBUG_FORMAT_MONO);
2627 #ifdef HOST_WIN32
2628 if (mixed_mode)
2629 mono_load_coree (argv [i]);
2630 #endif
2632 /* Parse gac loading options before loading assemblies. */
2633 if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER || action == DO_REGRESSION) {
2634 mono_config_parse (config_file);
2637 mono_set_defaults (mini_verbose_level, opt);
2638 mono_set_os_args (argc, argv);
2640 domain = mini_init (argv [i], forced_version);
2642 mono_gc_set_stack_end (&domain);
2644 if (agents) {
2645 int i;
2647 for (i = 0; i < agents->len; ++i) {
2648 int res = load_agent (domain, (char*)g_ptr_array_index (agents, i));
2649 if (res) {
2650 g_ptr_array_free (agents, TRUE);
2651 mini_cleanup (domain);
2652 return 1;
2656 g_ptr_array_free (agents, TRUE);
2659 switch (action) {
2660 case DO_SINGLE_METHOD_REGRESSION:
2661 case DO_REGRESSION:
2662 return mono_exec_regression_internal (mini_verbose_level, argc -i, argv + i, action == DO_SINGLE_METHOD_REGRESSION);
2664 case DO_BENCH:
2665 if (argc - i != 1 || mname == NULL) {
2666 g_print ("Usage: mini --ncompile num --compile method assembly\n");
2667 mini_cleanup (domain);
2668 return 1;
2670 aname = argv [i];
2671 break;
2672 case DO_COMPILE:
2673 if (argc - i != 1) {
2674 mini_usage ();
2675 mini_cleanup (domain);
2676 return 1;
2678 aname = argv [i];
2679 break;
2680 case DO_DRAW:
2681 if (argc - i != 1 || mname == NULL) {
2682 mini_usage ();
2683 mini_cleanup (domain);
2684 return 1;
2686 aname = argv [i];
2687 break;
2688 default:
2689 if (argc - i < 1) {
2690 mini_usage ();
2691 mini_cleanup (domain);
2692 return 1;
2694 aname = argv [i];
2695 break;
2698 #ifdef MONO_JIT_INFO_TABLE_TEST
2699 if (test_jit_info_table)
2700 jit_info_table_test (domain);
2701 #endif
2703 if (mono_compile_aot && extra_bindings_config_file != NULL) {
2704 apply_root_domain_configuration_file_bindings (domain, extra_bindings_config_file);
2707 MonoAssemblyOpenRequest open_req;
2708 mono_assembly_request_prepare_open (&open_req, MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_get_root_domain ()));
2709 assembly = mono_assembly_request_open (aname, &open_req, &open_status);
2710 if (!assembly && !mono_compile_aot) {
2711 fprintf (stderr, "Cannot open assembly '%s': %s.\n", aname, mono_image_strerror (open_status));
2712 mini_cleanup (domain);
2713 return 2;
2716 mono_callspec_set_assembly (assembly);
2718 if (mono_compile_aot || action == DO_EXEC) {
2719 const char *error;
2721 //mono_set_rootdir ();
2723 error = mono_check_corlib_version ();
2724 if (error) {
2725 fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
2726 fprintf (stderr, "Loaded from: %s\n",
2727 mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown");
2728 fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.mono-project.com/download.\n");
2729 exit (1);
2732 #if defined(HOST_WIN32) && HAVE_API_SUPPORT_WIN32_CONSOLE
2733 /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
2734 if (!enable_debugging && !mono_compile_aot && mono_assembly_get_image_internal (assembly)->image_info->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
2735 FreeConsole ();
2736 #endif
2738 main_args.domain = domain;
2739 main_args.file = aname;
2740 main_args.argc = argc - i;
2741 main_args.argv = argv + i;
2742 main_args.opts = opt;
2743 main_args.aot_options = aot_options;
2744 main_thread_handler (&main_args);
2745 mono_thread_manage_internal ();
2747 mini_cleanup (domain);
2749 /* Look up return value from System.Environment.ExitCode */
2750 i = mono_environment_exitcode_get ();
2751 return i;
2752 } else if (action == DO_COMPILE) {
2753 compile_all_methods (assembly, mini_verbose_level, opt, recompilation_times);
2754 mini_cleanup (domain);
2755 return 0;
2756 } else if (action == DO_DEBUGGER) {
2757 return 1;
2759 desc = mono_method_desc_new (mname, 0);
2760 if (!desc) {
2761 g_print ("Invalid method name %s\n", mname);
2762 mini_cleanup (domain);
2763 return 3;
2765 method = mono_method_desc_search_in_image (desc, mono_assembly_get_image_internal (assembly));
2766 if (!method) {
2767 g_print ("Cannot find method %s\n", mname);
2768 mini_cleanup (domain);
2769 return 3;
2772 #ifndef DISABLE_JIT
2773 MonoCompile *cfg;
2774 if (action == DO_DRAW) {
2775 int part = 0;
2777 switch (mono_graph_options) {
2778 case MONO_GRAPH_DTREE:
2779 part = 1;
2780 opt |= MONO_OPT_LOOP;
2781 break;
2782 case MONO_GRAPH_CFG_CODE:
2783 part = 1;
2784 break;
2785 case MONO_GRAPH_CFG_SSA:
2786 part = 2;
2787 break;
2788 case MONO_GRAPH_CFG_OPTCODE:
2789 part = 3;
2790 break;
2791 default:
2792 break;
2795 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2796 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
2797 MonoMethod *nm;
2798 nm = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
2799 cfg = mini_method_compile (nm, opt, mono_get_root_domain (), (JitFlags)0, part, -1);
2801 else
2802 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, part, -1);
2803 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
2804 g_warning ("no SSA info available (use -O=deadce)");
2805 return 1;
2807 mono_draw_graph (cfg, mono_graph_options);
2808 mono_destroy_compile (cfg);
2810 } else if (action == DO_BENCH) {
2811 if (mini_stats_fd) {
2812 const char *n;
2813 double no_opt_time = 0.0;
2814 GTimer *timer = g_timer_new ();
2815 fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n",
2816 mono_method_full_name (method, TRUE));
2817 fprintf (mini_stats_fd, "@data = (\n");
2818 fprintf (mini_stats_fd, "[");
2819 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
2820 opt = opt_sets [i];
2821 n = mono_opt_descr (opt);
2822 if (!n [0])
2823 n = "none";
2824 fprintf (mini_stats_fd, "\"%s\",", n);
2826 fprintf (mini_stats_fd, "],\n[");
2828 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
2829 int j;
2830 double elapsed;
2831 opt = opt_sets [i];
2832 g_timer_start (timer);
2833 for (j = 0; j < count; ++j) {
2834 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2835 mono_destroy_compile (cfg);
2837 g_timer_stop (timer);
2838 elapsed = g_timer_elapsed (timer, NULL);
2839 if (!opt)
2840 no_opt_time = elapsed;
2841 fprintf (mini_stats_fd, "%f, ", elapsed);
2843 fprintf (mini_stats_fd, "]");
2844 if (no_opt_time > 0.0) {
2845 fprintf (mini_stats_fd, ", \n[");
2846 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++)
2847 fprintf (mini_stats_fd, "%f,", no_opt_time);
2848 fprintf (mini_stats_fd, "]");
2850 fprintf (mini_stats_fd, ");\n");
2851 } else {
2852 for (i = 0; i < count; ++i) {
2853 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2854 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
2855 method = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
2857 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2858 mono_destroy_compile (cfg);
2861 } else {
2862 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2863 mono_destroy_compile (cfg);
2865 #endif
2867 mini_cleanup (domain);
2868 return 0;
2872 * mono_jit_init:
2874 MonoDomain *
2875 mono_jit_init (const char *file)
2877 MonoDomain *ret = mini_init (file, NULL);
2878 MONO_ENTER_GC_SAFE_UNBALANCED; //once it is not executing any managed code yet, it's safe to run the gc
2879 return ret;
2883 * mono_jit_init_version:
2884 * \param domain_name the name of the root domain
2885 * \param runtime_version the version of the runtime to load
2887 * Use this version when you want to force a particular runtime
2888 * version to be used. By default Mono will pick the runtime that is
2889 * referenced by the initial assembly (specified in \p file), this
2890 * routine allows programmers to specify the actual runtime to be used
2891 * as the initial runtime is inherited by all future assemblies loaded
2892 * (since Mono does not support having more than one mscorlib runtime
2893 * loaded at once).
2895 * The \p runtime_version can be one of these strings: "v4.0.30319" for
2896 * desktop, "mobile" for mobile or "moonlight" for Silverlight compat.
2897 * If an unrecognized string is input, the vm will default to desktop.
2899 * \returns the \c MonoDomain representing the domain where the assembly
2900 * was loaded.
2902 MonoDomain *
2903 mono_jit_init_version (const char *domain_name, const char *runtime_version)
2905 MonoDomain *ret = mini_init (domain_name, runtime_version);
2906 MONO_ENTER_GC_SAFE_UNBALANCED; //once it is not executing any managed code yet, it's safe to run the gc
2907 return ret;
2910 MonoDomain *
2911 mono_jit_init_version_for_test_only (const char *domain_name, const char *runtime_version)
2913 MonoDomain *ret = mini_init (domain_name, runtime_version);
2914 return ret;
2918 * mono_jit_cleanup:
2920 void
2921 mono_jit_cleanup (MonoDomain *domain)
2923 MONO_STACKDATA (dummy);
2924 (void) mono_threads_enter_gc_unsafe_region_unbalanced_internal (&dummy);
2926 // after mini_cleanup everything is cleaned up so MONO_EXIT_GC_UNSAFE
2927 // can't work and doesn't make sense.
2929 mono_thread_manage_internal ();
2931 mini_cleanup (domain);
2935 void
2936 mono_jit_set_aot_only (gboolean val)
2938 mono_aot_only = val;
2939 mono_ee_features.use_aot_trampolines = val;
2942 static void
2943 mono_runtime_set_execution_mode_full (int mode, gboolean override)
2945 static gboolean mode_initialized = FALSE;
2946 if (mode_initialized && !override)
2947 return;
2949 mode_initialized = TRUE;
2950 memset (&mono_ee_features, 0, sizeof (mono_ee_features));
2952 switch (mode) {
2953 case MONO_AOT_MODE_LLVMONLY:
2954 mono_aot_only = TRUE;
2955 mono_llvm_only = TRUE;
2957 mono_ee_features.use_aot_trampolines = TRUE;
2958 break;
2960 case MONO_AOT_MODE_FULL:
2961 mono_aot_only = TRUE;
2963 mono_ee_features.use_aot_trampolines = TRUE;
2964 break;
2966 case MONO_AOT_MODE_HYBRID:
2967 mono_set_generic_sharing_vt_supported (TRUE);
2968 mono_set_partial_sharing_supported (TRUE);
2969 break;
2971 case MONO_AOT_MODE_INTERP:
2972 mono_aot_only = TRUE;
2973 mono_use_interpreter = TRUE;
2975 mono_ee_features.use_aot_trampolines = TRUE;
2976 break;
2978 case MONO_AOT_MODE_INTERP_LLVMONLY:
2979 mono_aot_only = TRUE;
2980 mono_use_interpreter = TRUE;
2981 mono_llvm_only = TRUE;
2983 mono_ee_features.force_use_interpreter = TRUE;
2984 break;
2986 case MONO_AOT_MODE_LLVMONLY_INTERP:
2987 mono_aot_only = TRUE;
2988 mono_use_interpreter = TRUE;
2989 mono_llvm_only = TRUE;
2990 break;
2992 case MONO_AOT_MODE_INTERP_ONLY:
2993 mono_check_interp_supported ();
2994 mono_use_interpreter = TRUE;
2996 mono_ee_features.force_use_interpreter = TRUE;
2997 break;
2999 case MONO_AOT_MODE_NORMAL:
3000 case MONO_AOT_MODE_NONE:
3001 break;
3003 default:
3004 g_error ("Unknown execution-mode %d", mode);
3009 static void
3010 mono_runtime_set_execution_mode (int mode)
3012 mono_runtime_set_execution_mode_full (mode, TRUE);
3016 * mono_jit_set_aot_mode:
3018 void
3019 mono_jit_set_aot_mode (MonoAotMode mode)
3021 /* we don't want to set mono_aot_mode twice */
3022 static gboolean inited;
3024 g_assert (!inited);
3025 mono_aot_mode = mode;
3026 inited = TRUE;
3028 mono_runtime_set_execution_mode (mode);
3031 mono_bool
3032 mono_jit_aot_compiling (void)
3034 return mono_compile_aot;
3038 * mono_jit_set_trace_options:
3039 * \param options string representing the trace options
3040 * Set the options of the tracing engine. This function can be called before initializing
3041 * the mono runtime. See the --trace mono(1) manpage for the options format.
3043 * \returns TRUE if the options were parsed and set correctly, FALSE otherwise.
3045 gboolean
3046 mono_jit_set_trace_options (const char* options)
3048 MonoCallSpec *trace_opt = mono_trace_set_options (options);
3049 if (trace_opt == NULL)
3050 return FALSE;
3051 mono_jit_trace_calls = trace_opt;
3052 return TRUE;
3056 * mono_set_signal_chaining:
3058 * Enable/disable signal chaining. This should be called before \c mono_jit_init.
3059 * If signal chaining is enabled, the runtime saves the original signal handlers before
3060 * installing its own handlers, and calls the original ones in the following cases:
3061 * - a \c SIGSEGV / \c SIGABRT signal received while executing native (i.e. not JITted) code.
3062 * - \c SIGPROF
3063 * - \c SIGFPE
3064 * - \c SIGQUIT
3065 * - \c SIGUSR2
3066 * Signal chaining only works on POSIX platforms.
3068 void
3069 mono_set_signal_chaining (gboolean chain_signals)
3071 mono_do_signal_chaining = chain_signals;
3075 * mono_set_crash_chaining:
3077 * Enable/disable crash chaining due to signals. When a fatal signal is delivered and
3078 * Mono doesn't know how to handle it, it will invoke the crash handler. If chrash chaining
3079 * is enabled, it will first print its crash information and then try to chain with the native handler.
3081 void
3082 mono_set_crash_chaining (gboolean chain_crashes)
3084 mono_do_crash_chaining = chain_crashes;
3088 * mono_parse_options_from:
3089 * \param options string containing strings
3090 * \param ref_argc pointer to the \c argc variable that might be updated
3091 * \param ref_argv pointer to the \c argv string vector variable that might be updated
3093 * This function parses the contents of the \c MONO_ENV_OPTIONS
3094 * environment variable as if they were parsed by a command shell
3095 * splitting the contents by spaces into different elements of the
3096 * \p argv vector. This method supports quoting with both the " and '
3097 * characters. Inside quoting, spaces and tabs are significant,
3098 * otherwise, they are considered argument separators.
3100 * The \ character can be used to escape the next character which will
3101 * be added to the current element verbatim. Typically this is used
3102 * inside quotes. If the quotes are not balanced, this method
3104 * If the environment variable is empty, no changes are made
3105 * to the values pointed by \p ref_argc and \p ref_argv.
3107 * Otherwise the \p ref_argv is modified to point to a new array that contains
3108 * all the previous elements contained in the vector, plus the values parsed.
3109 * The \p argc is updated to match the new number of parameters.
3111 * \returns The value NULL is returned on success, otherwise a \c g_strdup allocated
3112 * string is returned (this is an alias to \c malloc under normal circumstances) that
3113 * contains the error message that happened during parsing.
3115 char *
3116 mono_parse_options_from (const char *options, int *ref_argc, char **ref_argv [])
3118 return mono_parse_options (options, ref_argc, ref_argv, TRUE);
3121 static void
3122 merge_parsed_options (GPtrArray *parsed_options, int *ref_argc, char **ref_argv [], gboolean prepend)
3124 int argc = *ref_argc;
3125 char **argv = *ref_argv;
3127 if (parsed_options->len > 0){
3128 int new_argc = parsed_options->len + argc;
3129 char **new_argv = g_new (char *, new_argc + 1);
3130 guint i;
3131 guint j;
3133 new_argv [0] = argv [0];
3135 i = 1;
3136 if (prepend){
3137 /* First the environment variable settings, to allow the command line options to override */
3138 for (i = 0; i < parsed_options->len; i++)
3139 new_argv [i+1] = (char *)g_ptr_array_index (parsed_options, i);
3140 i++;
3142 for (j = 1; j < argc; j++)
3143 new_argv [i++] = argv [j];
3144 if (!prepend){
3145 for (j = 0; j < parsed_options->len; j++)
3146 new_argv [i++] = (char *)g_ptr_array_index (parsed_options, j);
3148 new_argv [i] = NULL;
3150 *ref_argc = new_argc;
3151 *ref_argv = new_argv;
3155 static char *
3156 mono_parse_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3158 if (options == NULL)
3159 return NULL;
3161 GPtrArray *array = g_ptr_array_new ();
3162 GString *buffer = g_string_new ("");
3163 const char *p;
3164 gboolean in_quotes = FALSE;
3165 char quote_char = '\0';
3167 for (p = options; *p; p++){
3168 switch (*p){
3169 case ' ': case '\t': case '\n':
3170 if (!in_quotes) {
3171 if (buffer->len != 0){
3172 g_ptr_array_add (array, g_strdup (buffer->str));
3173 g_string_truncate (buffer, 0);
3175 } else {
3176 g_string_append_c (buffer, *p);
3178 break;
3179 case '\\':
3180 if (p [1]){
3181 g_string_append_c (buffer, p [1]);
3182 p++;
3184 break;
3185 case '\'':
3186 case '"':
3187 if (in_quotes) {
3188 if (quote_char == *p)
3189 in_quotes = FALSE;
3190 else
3191 g_string_append_c (buffer, *p);
3192 } else {
3193 in_quotes = TRUE;
3194 quote_char = *p;
3196 break;
3197 default:
3198 g_string_append_c (buffer, *p);
3199 break;
3202 if (in_quotes)
3203 return g_strdup_printf ("Unmatched quotes in value: [%s]\n", options);
3205 if (buffer->len != 0)
3206 g_ptr_array_add (array, g_strdup (buffer->str));
3207 g_string_free (buffer, TRUE);
3209 merge_parsed_options (array, ref_argc, ref_argv, prepend);
3210 g_ptr_array_free (array, TRUE);
3212 return NULL;
3215 #if defined(HOST_WIN32) && HAVE_API_SUPPORT_WIN32_COMMAND_LINE_TO_ARGV
3216 #include <shellapi.h>
3218 static char *
3219 mono_win32_parse_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3221 int argc;
3222 gunichar2 **argv;
3223 gunichar2 *optionsw;
3225 if (!options)
3226 return NULL;
3228 GPtrArray *array = g_ptr_array_new ();
3229 optionsw = g_utf8_to_utf16 (options, -1, NULL, NULL, NULL);
3230 if (optionsw) {
3231 gunichar2 *p;
3232 gboolean in_quotes = FALSE;
3233 gunichar2 quote_char = L'\0';
3234 for (p = optionsw; *p; p++){
3235 switch (*p){
3236 case L'\n':
3237 if (!in_quotes)
3238 *p = L' ';
3239 break;
3240 case L'\'':
3241 case L'"':
3242 if (in_quotes) {
3243 if (quote_char == *p)
3244 in_quotes = FALSE;
3245 } else {
3246 in_quotes = TRUE;
3247 quote_char = *p;
3249 break;
3253 argv = CommandLineToArgvW (optionsw, &argc);
3254 if (argv) {
3255 for (int i = 0; i < argc; i++)
3256 g_ptr_array_add (array, g_utf16_to_utf8 (argv[i], -1, NULL, NULL, NULL));
3258 LocalFree (argv);
3261 g_free (optionsw);
3264 merge_parsed_options (array, ref_argc, ref_argv, prepend);
3265 g_ptr_array_free (array, TRUE);
3267 return NULL;
3270 static char *
3271 mono_parse_response_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3273 return mono_win32_parse_options (options, ref_argc, ref_argv, prepend);
3275 #else
3276 static char *
3277 mono_parse_response_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
3279 return mono_parse_options (options, ref_argc, ref_argv, prepend);
3281 #endif
3284 * mono_parse_env_options:
3285 * \param ref_argc pointer to the \c argc variable that might be updated
3286 * \param ref_argv pointer to the \c argv string vector variable that might be updated
3288 * This function parses the contents of the \c MONO_ENV_OPTIONS
3289 * environment variable as if they were parsed by a command shell
3290 * splitting the contents by spaces into different elements of the
3291 * \p argv vector. This method supports quoting with both the " and '
3292 * characters. Inside quoting, spaces and tabs are significant,
3293 * otherwise, they are considered argument separators.
3295 * The \ character can be used to escape the next character which will
3296 * be added to the current element verbatim. Typically this is used
3297 * inside quotes. If the quotes are not balanced, this method
3299 * If the environment variable is empty, no changes are made
3300 * to the values pointed by \p ref_argc and \p ref_argv.
3302 * Otherwise the \p ref_argv is modified to point to a new array that contains
3303 * all the previous elements contained in the vector, plus the values parsed.
3304 * The \p argc is updated to match the new number of parameters.
3306 * If there is an error parsing, this method will terminate the process by
3307 * calling exit(1).
3309 * An alternative to this method that allows an arbitrary string to be parsed
3310 * and does not exit on error is the `api:mono_parse_options_from`.
3312 void
3313 mono_parse_env_options (int *ref_argc, char **ref_argv [])
3315 char *ret;
3317 char *env_options = g_getenv ("MONO_ENV_OPTIONS");
3318 if (env_options == NULL)
3319 return;
3320 ret = mono_parse_options_from (env_options, ref_argc, ref_argv);
3321 g_free (env_options);
3322 if (ret == NULL)
3323 return;
3324 fprintf (stderr, "%s", ret);
3325 exit (1);