[runtime] Fix aot mode double init check
[mono-project.git] / mono / mini / driver.c
blob866481abb7c3b4956e8c36c62ac7f14e1de819a4
1 /**
2 * \file
3 * The new mono JIT compiler.
5 * Author:
6 * Paolo Molaro (lupus@ximian.com)
7 * Dietmar Maurer (dietmar@ximian.com)
9 * (C) 2002-2003 Ximian, Inc.
10 * (C) 2003-2006 Novell, Inc.
11 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14 #include <config.h>
15 #ifdef HAVE_SIGNAL_H
16 #include <signal.h>
17 #endif
18 #if HAVE_SCHED_SETAFFINITY
19 #include <sched.h>
20 #endif
21 #ifdef HAVE_UNISTD_H
22 #include <unistd.h>
23 #endif
25 #include <mono/metadata/assembly-internals.h>
26 #include <mono/metadata/loader.h>
27 #include <mono/metadata/tabledefs.h>
28 #include <mono/metadata/class.h>
29 #include <mono/metadata/object.h>
30 #include <mono/metadata/exception.h>
31 #include <mono/metadata/opcodes.h>
32 #include <mono/metadata/mono-endian.h>
33 #include <mono/metadata/tokentype.h>
34 #include <mono/metadata/reflection-internals.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/threads.h>
37 #include <mono/metadata/marshal.h>
38 #include <mono/metadata/appdomain.h>
39 #include <mono/metadata/debug-helpers.h>
40 #include <mono/metadata/profiler-private.h>
41 #include <mono/metadata/mono-config.h>
42 #include <mono/metadata/environment.h>
43 #include <mono/metadata/verify.h>
44 #include <mono/metadata/verify-internals.h>
45 #include <mono/metadata/mono-debug.h>
46 #include <mono/metadata/security-manager.h>
47 #include <mono/metadata/security-core-clr.h>
48 #include <mono/metadata/gc-internals.h>
49 #include <mono/metadata/coree.h>
50 #include <mono/metadata/attach.h>
51 #include <mono/metadata/w32process.h>
52 #include "mono/utils/mono-counters.h"
53 #include "mono/utils/mono-hwcap.h"
54 #include "mono/utils/mono-logger-internals.h"
55 #include "mono/metadata/w32handle.h"
56 #include "mono/metadata/callspec.h"
57 #include "mono/metadata/custom-attrs-internals.h"
59 #include "mini.h"
60 #include "jit.h"
61 #include "aot-compiler.h"
62 #include "aot-runtime.h"
63 #include "mini-runtime.h"
64 #include "interp/interp.h"
66 #include <string.h>
67 #include <ctype.h>
68 #include <locale.h>
69 #include "version.h"
70 #include "debugger-agent.h"
71 #if TARGET_OSX
72 # include <sys/resource.h>
73 #endif
75 static FILE *mini_stats_fd;
77 static void mini_usage (void);
78 static void mono_runtime_set_execution_mode (MonoEEMode mode);
79 static int mono_jit_exec_internal (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[]);
81 #ifdef HOST_WIN32
82 /* Need this to determine whether to detach console */
83 #include <mono/metadata/cil-coff.h>
84 /* This turns off command line globbing under win32 */
85 int _CRT_glob = 0;
86 #endif
88 typedef void (*OptFunc) (const char *p);
90 #undef OPTFLAG
92 // This, instead of an array of pointers, to optimize away a pointer and a relocation per string.
93 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
94 #define MSGSTRFIELD1(line) str##line
96 static const struct msgstr_t {
97 #define OPTFLAG(id,shift,name,desc) char MSGSTRFIELD(__LINE__) [sizeof (name) + sizeof (desc)];
98 #include "optflags-def.h"
99 #undef OPTFLAG
100 } opstr = {
101 #define OPTFLAG(id,shift,name,desc) name "\0" desc,
102 #include "optflags-def.h"
103 #undef OPTFLAG
105 static const gint16 opt_names [] = {
106 #define OPTFLAG(id,shift,name,desc) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
107 #include "optflags-def.h"
108 #undef OPTFLAG
111 #define optflag_get_name(id) ((const char*)&opstr + opt_names [(id)])
112 #define optflag_get_desc(id) (optflag_get_name(id) + 1 + strlen (optflag_get_name(id)))
114 #define DEFAULT_OPTIMIZATIONS ( \
115 MONO_OPT_PEEPHOLE | \
116 MONO_OPT_CFOLD | \
117 MONO_OPT_INLINE | \
118 MONO_OPT_CONSPROP | \
119 MONO_OPT_COPYPROP | \
120 MONO_OPT_DEADCE | \
121 MONO_OPT_BRANCH | \
122 MONO_OPT_LINEARS | \
123 MONO_OPT_INTRINS | \
124 MONO_OPT_LOOP | \
125 MONO_OPT_EXCEPTION | \
126 MONO_OPT_CMOV | \
127 MONO_OPT_GSHARED | \
128 MONO_OPT_SIMD | \
129 MONO_OPT_ALIAS_ANALYSIS | \
130 MONO_OPT_AOT | \
131 MONO_OPT_FLOAT32)
133 #define EXCLUDED_FROM_ALL (MONO_OPT_SHARED | MONO_OPT_PRECOMP | MONO_OPT_UNSAFE | MONO_OPT_GSHAREDVT)
135 static char *mono_parse_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend);
137 static guint32
138 parse_optimizations (guint32 opt, const char* p, gboolean cpu_opts)
140 guint32 exclude = 0;
141 const char *n;
142 int i, invert;
143 char **parts, **ptr;
145 /* Initialize the hwcap module if necessary. */
146 mono_hwcap_init ();
148 /* call out to cpu detection code here that sets the defaults ... */
149 if (cpu_opts) {
150 #ifndef MONO_CROSS_COMPILE
151 opt |= mono_arch_cpu_optimizations (&exclude);
152 opt &= ~exclude;
153 #endif
155 if (!p)
156 return opt;
158 parts = g_strsplit (p, ",", -1);
159 for (ptr = parts; ptr && *ptr; ptr ++) {
160 char *arg = *ptr;
161 char *p = arg;
163 if (*p == '-') {
164 p++;
165 invert = TRUE;
166 } else {
167 invert = FALSE;
169 for (i = 0; i < G_N_ELEMENTS (opt_names) && optflag_get_name (i); ++i) {
170 n = optflag_get_name (i);
171 if (!strcmp (p, n)) {
172 if (invert)
173 opt &= ~ (1 << i);
174 else
175 opt |= 1 << i;
176 break;
179 if (i == G_N_ELEMENTS (opt_names) || !optflag_get_name (i)) {
180 if (strncmp (p, "all", 3) == 0) {
181 if (invert)
182 opt = 0;
183 else
184 opt = ~(EXCLUDED_FROM_ALL | exclude);
185 } else {
186 fprintf (stderr, "Invalid optimization name `%s'\n", p);
187 exit (1);
191 g_free (arg);
193 g_free (parts);
195 return opt;
198 static gboolean
199 parse_debug_options (const char* p)
201 MonoDebugOptions *opt = mini_get_debug_options ();
203 do {
204 if (!*p) {
205 fprintf (stderr, "Syntax error; expected debug option name\n");
206 return FALSE;
209 if (!strncmp (p, "casts", 5)) {
210 opt->better_cast_details = TRUE;
211 p += 5;
212 } else if (!strncmp (p, "mdb-optimizations", 17)) {
213 opt->mdb_optimizations = TRUE;
214 p += 17;
215 } else if (!strncmp (p, "gdb", 3)) {
216 opt->gdb = TRUE;
217 p += 3;
218 } else {
219 fprintf (stderr, "Invalid debug option `%s', use --help-debug for details\n", p);
220 return FALSE;
223 if (*p == ',') {
224 p++;
225 if (!*p) {
226 fprintf (stderr, "Syntax error; expected debug option name\n");
227 return FALSE;
230 } while (*p);
232 return TRUE;
235 typedef struct {
236 const char name [6];
237 const char desc [18];
238 MonoGraphOptions value;
239 } GraphName;
241 static const GraphName
242 graph_names [] = {
243 {"cfg", "Control Flow", MONO_GRAPH_CFG},
244 {"dtree", "Dominator Tree", MONO_GRAPH_DTREE},
245 {"code", "CFG showing code", MONO_GRAPH_CFG_CODE},
246 {"ssa", "CFG after SSA", MONO_GRAPH_CFG_SSA},
247 {"optc", "CFG after IR opts", MONO_GRAPH_CFG_OPTCODE}
250 static MonoGraphOptions
251 mono_parse_graph_options (const char* p)
253 const char *n;
254 int i, len;
256 for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
257 n = graph_names [i].name;
258 len = strlen (n);
259 if (strncmp (p, n, len) == 0)
260 return graph_names [i].value;
263 fprintf (stderr, "Invalid graph name provided: %s\n", p);
264 exit (1);
268 * mono_parse_default_optimizations:
271 mono_parse_default_optimizations (const char* p)
273 guint32 opt;
275 opt = parse_optimizations (DEFAULT_OPTIMIZATIONS, p, TRUE);
276 return opt;
279 char*
280 mono_opt_descr (guint32 flags) {
281 GString *str = g_string_new ("");
282 int i, need_comma;
284 need_comma = 0;
285 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
286 if (flags & (1 << i) && optflag_get_name (i)) {
287 if (need_comma)
288 g_string_append_c (str, ',');
289 g_string_append (str, optflag_get_name (i));
290 need_comma = 1;
293 return g_string_free (str, FALSE);
296 static const guint32
297 opt_sets [] = {
299 MONO_OPT_PEEPHOLE,
300 MONO_OPT_BRANCH,
301 MONO_OPT_CFOLD,
302 MONO_OPT_FCMOV,
303 MONO_OPT_ALIAS_ANALYSIS,
304 #ifdef MONO_ARCH_SIMD_INTRINSICS
305 MONO_OPT_SIMD | MONO_OPT_INTRINS,
306 MONO_OPT_SSE2,
307 MONO_OPT_SIMD | MONO_OPT_SSE2 | MONO_OPT_INTRINS,
308 #endif
309 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS,
310 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS | MONO_OPT_ALIAS_ANALYSIS,
311 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS,
312 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP,
313 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_CFOLD,
314 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE,
315 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_ALIAS_ANALYSIS,
316 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,
317 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_TAILCALL,
318 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_SSA,
319 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_EXCEPTION,
320 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_EXCEPTION | MONO_OPT_CMOV,
321 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_EXCEPTION | MONO_OPT_ABCREM,
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_ABCREM,
323 MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_LOOP | MONO_OPT_INLINE | MONO_OPT_INTRINS | MONO_OPT_ABCREM | MONO_OPT_SHARED,
324 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,
325 DEFAULT_OPTIMIZATIONS,
328 typedef int (*TestMethod) (void);
330 #if 0
331 static void
332 domain_dump_native_code (MonoDomain *domain) {
333 // need to poke into the domain, move to metadata/domain.c
334 // need to empty jit_info_table and code_mp
336 #endif
338 static gboolean do_regression_retries;
339 static int regression_test_skip_index;
342 static gboolean
343 method_should_be_regression_tested (MonoMethod *method, gboolean interp)
345 ERROR_DECL (error);
347 if (strncmp (method->name, "test_", 5) != 0)
348 return FALSE;
350 static gboolean filter_method_init = FALSE;
351 static const char *filter_method = NULL;
353 if (!filter_method_init) {
354 filter_method = g_getenv ("REGRESSION_FILTER_METHOD");
355 filter_method_init = TRUE;
358 if (filter_method) {
359 const char *name = filter_method;
361 if ((strchr (name, '.') > name) || strchr (name, ':')) {
362 MonoMethodDesc *desc = mono_method_desc_new (name, TRUE);
363 gboolean res = mono_method_desc_full_match (desc, method);
364 mono_method_desc_free (desc);
365 return res;
366 } else {
367 return strcmp (method->name, name) == 0;
371 MonoCustomAttrInfo* ainfo = mono_custom_attrs_from_method_checked (method, error);
372 mono_error_cleanup (error);
373 if (!ainfo)
374 return TRUE;
376 int j;
377 for (j = 0; j < ainfo->num_attrs; ++j) {
378 MonoCustomAttrEntry *centry = &ainfo->attrs [j];
379 if (centry->ctor == NULL)
380 continue;
382 MonoClass *klass = centry->ctor->klass;
383 if (strcmp (m_class_get_name (klass), "CategoryAttribute") || mono_method_signature_internal (centry->ctor)->param_count != 1)
384 continue;
386 gpointer *typed_args, *named_args;
387 int num_named_args;
388 CattrNamedArg *arginfo;
390 mono_reflection_create_custom_attr_data_args_noalloc (
391 mono_defaults.corlib, centry->ctor, centry->data, centry->data_size,
392 &typed_args, &named_args, &num_named_args, &arginfo, error);
393 if (!is_ok (error))
394 continue;
396 char *utf8_str = (char*)(void*)typed_args[0]; //this points into image memory that is constant
397 g_free (typed_args);
398 g_free (named_args);
399 g_free (arginfo);
401 if (interp && !strcmp (utf8_str, "!INTERPRETER")) {
402 g_print ("skip %s...\n", method->name);
403 return FALSE;
406 #if HOST_WASM
407 if (!strcmp (utf8_str, "!WASM")) {
408 g_print ("skip %s...\n", method->name);
409 return FALSE;
411 #endif
412 if (mono_aot_mode == MONO_AOT_MODE_FULL && !strcmp (utf8_str, "!FULLAOT")) {
413 g_print ("skip %s...\n", method->name);
414 return FALSE;
417 if ((mono_aot_mode == MONO_AOT_MODE_INTERP_LLVMONLY || mono_aot_mode == MONO_AOT_MODE_LLVMONLY) && !strcmp (utf8_str, "!BITCODE")) {
418 g_print ("skip %s...\n", method->name);
419 return FALSE;
423 return TRUE;
426 static void
427 mini_regression_step (MonoImage *image, int verbose, int *total_run, int *total,
428 guint32 opt_flags,
429 GTimer *timer, MonoDomain *domain)
431 int result, expected, failed, cfailed, run, code_size;
432 double elapsed, comp_time, start_time;
433 char *n;
434 int i;
436 mono_set_defaults (verbose, opt_flags);
437 n = mono_opt_descr (opt_flags);
438 g_print ("Test run: image=%s, opts=%s\n", mono_image_get_filename (image), n);
439 g_free (n);
440 cfailed = failed = run = code_size = 0;
441 comp_time = elapsed = 0.0;
442 int local_skip_index = 0;
444 /* fixme: ugly hack - delete all previously compiled methods */
445 if (domain_jit_info (domain)) {
446 g_hash_table_destroy (domain_jit_info (domain)->jit_trampoline_hash);
447 domain_jit_info (domain)->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
448 mono_internal_hash_table_destroy (&(domain->jit_code_hash));
449 mono_jit_code_hash_init (&(domain->jit_code_hash));
452 g_timer_start (timer);
453 if (mini_stats_fd)
454 fprintf (mini_stats_fd, "[");
455 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
456 ERROR_DECL (error);
457 MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
458 if (!method) {
459 mono_error_cleanup (error); /* FIXME don't swallow the error */
460 continue;
462 if (method_should_be_regression_tested (method, FALSE)) {
463 MonoCompile *cfg = NULL;
464 TestMethod func = NULL;
466 expected = atoi (method->name + 5);
467 run++;
468 start_time = g_timer_elapsed (timer, NULL);
470 #ifdef DISABLE_JIT
471 #ifdef MONO_USE_AOT_COMPILER
472 ERROR_DECL (error);
473 func = (TestMethod)mono_aot_get_method (mono_get_root_domain (), method, error);
474 mono_error_cleanup (error);
475 #else
476 g_error ("No JIT or AOT available, regression testing not possible!")
477 #endif
479 #else
480 comp_time -= start_time;
481 cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, opt_flags), mono_get_root_domain (), JIT_FLAG_RUN_CCTORS, 0, -1);
482 comp_time += g_timer_elapsed (timer, NULL);
483 if (cfg->exception_type == MONO_EXCEPTION_NONE) {
484 #ifdef MONO_USE_AOT_COMPILER
485 ERROR_DECL (error);
486 func = (TestMethod)mono_aot_get_method (mono_get_root_domain (), method, error);
487 mono_error_cleanup (error);
488 if (!func)
489 func = (TestMethod)(gpointer)cfg->native_code;
490 #else
491 func = (TestMethod)(gpointer)cfg->native_code;
492 #endif
493 func = (TestMethod)mono_create_ftnptr (mono_get_root_domain (), (gpointer)func);
495 #endif
497 if (func) {
498 if (do_regression_retries) {
499 ++local_skip_index;
501 if(local_skip_index <= regression_test_skip_index)
502 continue;
503 ++regression_test_skip_index;
506 if (verbose >= 2)
507 g_print ("Running '%s' ...\n", method->name);
509 #if HOST_WASM
510 //WASM AOT injects dummy args and we must call with exact signatures
511 int (*func_2)(int) = (int (*)(int))(void*)func;
512 result = func_2 (-1);
513 #else
514 result = func ();
515 #endif
516 if (result != expected) {
517 failed++;
518 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
520 if (cfg) {
521 code_size += cfg->code_len;
522 mono_destroy_compile (cfg);
524 } else {
525 cfailed++;
526 g_print ("Test '%s' failed compilation.\n", method->name);
528 if (mini_stats_fd)
529 fprintf (mini_stats_fd, "%f, ",
530 g_timer_elapsed (timer, NULL) - start_time);
533 if (mini_stats_fd)
534 fprintf (mini_stats_fd, "],\n");
535 g_timer_stop (timer);
536 elapsed = g_timer_elapsed (timer, NULL);
537 if (failed > 0 || cfailed > 0){
538 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n",
539 run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
540 } else {
541 g_print ("Results: total tests: %d, all pass \n", run);
544 g_print ("Elapsed time: %f secs (%f, %f), Code size: %d\n\n", elapsed,
545 elapsed - comp_time, comp_time, code_size);
546 *total += failed + cfailed;
547 *total_run += run;
550 static int
551 mini_regression (MonoImage *image, int verbose, int *total_run)
553 guint32 i, opt;
554 MonoMethod *method;
555 char *n;
556 GTimer *timer = g_timer_new ();
557 MonoDomain *domain = mono_domain_get ();
558 guint32 exclude = 0;
559 int total;
561 /* Note: mono_hwcap_init () called in mono_init () before we get here. */
562 mono_arch_cpu_optimizations (&exclude);
564 if (mini_stats_fd) {
565 fprintf (mini_stats_fd, "$stattitle = \'Mono Benchmark Results (various optimizations)\';\n");
567 fprintf (mini_stats_fd, "$graph->set_legend(qw(");
568 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); opt++) {
569 guint32 opt_flags = opt_sets [opt];
570 n = mono_opt_descr (opt_flags);
571 if (!n [0])
572 n = (char *)"none";
573 if (opt)
574 fprintf (mini_stats_fd, " ");
575 fprintf (mini_stats_fd, "%s", n);
579 fprintf (mini_stats_fd, "));\n");
581 fprintf (mini_stats_fd, "@data = (\n");
582 fprintf (mini_stats_fd, "[");
585 /* load the metadata */
586 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
587 ERROR_DECL (error);
588 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
589 if (!method) {
590 mono_error_cleanup (error);
591 continue;
593 mono_class_init_internal (method->klass);
595 if (!strncmp (method->name, "test_", 5) && mini_stats_fd) {
596 fprintf (mini_stats_fd, "\"%s\",", method->name);
599 if (mini_stats_fd)
600 fprintf (mini_stats_fd, "],\n");
603 total = 0;
604 *total_run = 0;
605 if (mono_do_single_method_regression) {
606 GSList *iter;
608 mini_regression_step (image, verbose, total_run, &total,
610 timer, domain);
611 if (total)
612 return total;
613 g_print ("Single method regression: %d methods\n", g_slist_length (mono_single_method_list));
615 for (iter = mono_single_method_list; iter; iter = g_slist_next (iter)) {
616 char *method_name;
618 mono_current_single_method = (MonoMethod *)iter->data;
620 method_name = mono_method_full_name (mono_current_single_method, TRUE);
621 g_print ("Current single method: %s\n", method_name);
622 g_free (method_name);
624 mini_regression_step (image, verbose, total_run, &total,
626 timer, domain);
627 if (total)
628 return total;
630 } else {
631 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); ++opt) {
632 /* builtin-types.cs & aot-tests.cs need OPT_INTRINS enabled */
633 if (!strcmp ("builtin-types", image->assembly_name) || !strcmp ("aot-tests", image->assembly_name))
634 if (!(opt_sets [opt] & MONO_OPT_INTRINS))
635 continue;
637 //we running in AOT only, it makes no sense to try multiple flags
638 if ((mono_aot_mode == MONO_AOT_MODE_FULL || mono_aot_mode == MONO_AOT_MODE_LLVMONLY) && opt_sets [opt] != DEFAULT_OPTIMIZATIONS) {
639 continue;
642 mini_regression_step (image, verbose, total_run, &total,
643 opt_sets [opt] & ~exclude,
644 timer, domain);
648 if (mini_stats_fd) {
649 fprintf (mini_stats_fd, ");\n");
650 fflush (mini_stats_fd);
653 g_timer_destroy (timer);
654 return total;
657 static int
658 mini_regression_list (int verbose, int count, char *images [])
660 int i, total, total_run, run;
661 MonoAssembly *ass;
663 total_run = total = 0;
664 for (i = 0; i < count; ++i) {
665 MonoAssemblyOpenRequest req;
666 mono_assembly_request_prepare (&req.request, sizeof (req), MONO_ASMCTX_DEFAULT);
667 ass = mono_assembly_request_open (images [i], &req, NULL);
668 if (!ass) {
669 g_warning ("failed to load assembly: %s", images [i]);
670 continue;
672 total += mini_regression (mono_assembly_get_image_internal (ass), verbose, &run);
673 total_run += run;
675 if (total > 0){
676 g_print ("Overall results: tests: %d, failed: %d, opt combinations: %d (pass: %.2f%%)\n",
677 total_run, total, (int)G_N_ELEMENTS (opt_sets), 100.0*(total_run-total)/total_run);
678 } else {
679 g_print ("Overall results: tests: %d, 100%% pass, opt combinations: %d\n",
680 total_run, (int)G_N_ELEMENTS (opt_sets));
683 return total;
686 static void
687 interp_regression_step (MonoImage *image, int verbose, int *total_run, int *total, GTimer *timer, MonoDomain *domain)
689 int result, expected, failed, cfailed, run;
690 double elapsed, transform_time;
691 int i;
692 MonoObject *result_obj;
693 int local_skip_index = 0;
695 g_print ("Test run: image=%s\n", mono_image_get_filename (image));
696 cfailed = failed = run = 0;
697 transform_time = elapsed = 0.0;
699 g_timer_start (timer);
700 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
701 ERROR_DECL (error);
702 MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
703 if (!method) {
704 mono_error_cleanup (error); /* FIXME don't swallow the error */
705 continue;
708 if (method_should_be_regression_tested (method, TRUE)) {
709 ERROR_DECL (interp_error);
710 MonoObject *exc = NULL;
712 if (do_regression_retries) {
713 ++local_skip_index;
715 if(local_skip_index <= regression_test_skip_index)
716 continue;
717 ++regression_test_skip_index;
720 result_obj = mini_get_interp_callbacks ()->runtime_invoke (method, NULL, NULL, &exc, interp_error);
721 if (!mono_error_ok (interp_error)) {
722 cfailed++;
723 g_print ("Test '%s' execution failed.\n", method->name);
724 } else if (exc != NULL) {
725 g_print ("Exception in Test '%s' occured:\n", method->name);
726 mono_object_describe (exc);
727 run++;
728 failed++;
729 } else {
730 result = *(gint32 *) mono_object_unbox_internal (result_obj);
731 expected = atoi (method->name + 5); // FIXME: oh no.
732 run++;
734 if (result != expected) {
735 failed++;
736 g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
741 g_timer_stop (timer);
742 elapsed = g_timer_elapsed (timer, NULL);
743 if (failed > 0 || cfailed > 0){
744 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n",
745 run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
746 } else {
747 g_print ("Results: total tests: %d, all pass \n", run);
750 g_print ("Elapsed time: %f secs (%f, %f)\n\n", elapsed,
751 elapsed - transform_time, transform_time);
752 *total += failed + cfailed;
753 *total_run += run;
756 static int
757 interp_regression (MonoImage *image, int verbose, int *total_run)
759 MonoMethod *method;
760 GTimer *timer = g_timer_new ();
761 MonoDomain *domain = mono_domain_get ();
762 guint32 i;
763 int total;
765 /* load the metadata */
766 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
767 ERROR_DECL (error);
768 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
769 if (!method) {
770 mono_error_cleanup (error);
771 continue;
773 mono_class_init_internal (method->klass);
776 total = 0;
777 *total_run = 0;
778 interp_regression_step (image, verbose, total_run, &total, timer, domain);
780 g_timer_destroy (timer);
781 return total;
784 /* TODO: merge this code with the regression harness of the JIT */
785 static int
786 mono_interp_regression_list (int verbose, int count, char *images [])
788 int i, total, total_run, run;
790 total_run = total = 0;
791 for (i = 0; i < count; ++i) {
792 MonoAssemblyOpenRequest req;
793 mono_assembly_request_prepare (&req.request, sizeof (req), MONO_ASMCTX_DEFAULT);
794 MonoAssembly *ass = mono_assembly_request_open (images [i], &req, NULL);
795 if (!ass) {
796 g_warning ("failed to load assembly: %s", images [i]);
797 continue;
799 total += interp_regression (mono_assembly_get_image_internal (ass), verbose, &run);
800 total_run += run;
802 if (total > 0) {
803 g_print ("Overall results: tests: %d, failed: %d (pass: %.2f%%)\n", total_run, total, 100.0*(total_run-total)/total_run);
804 } else {
805 g_print ("Overall results: tests: %d, 100%% pass\n", total_run);
808 return total;
812 #ifdef MONO_JIT_INFO_TABLE_TEST
813 typedef struct _JitInfoData
815 guint start;
816 guint length;
817 MonoJitInfo *ji;
818 struct _JitInfoData *next;
819 } JitInfoData;
821 typedef struct
823 guint start;
824 guint length;
825 int num_datas;
826 JitInfoData *data;
827 } Region;
829 typedef struct
831 int num_datas;
832 int num_regions;
833 Region *regions;
834 int num_frees;
835 JitInfoData *frees;
836 } ThreadData;
838 static int num_threads;
839 static ThreadData *thread_datas;
840 static MonoDomain *test_domain;
842 static JitInfoData*
843 alloc_random_data (Region *region)
845 JitInfoData **data;
846 JitInfoData *prev;
847 guint prev_end;
848 guint next_start;
849 guint max_len;
850 JitInfoData *d;
851 int num_retries = 0;
852 int pos, i;
854 restart:
855 prev = NULL;
856 data = &region->data;
857 pos = random () % (region->num_datas + 1);
858 i = 0;
859 while (*data != NULL) {
860 if (i++ == pos)
861 break;
862 prev = *data;
863 data = &(*data)->next;
866 if (prev == NULL)
867 g_assert (*data == region->data);
868 else
869 g_assert (prev->next == *data);
871 if (prev == NULL)
872 prev_end = region->start;
873 else
874 prev_end = prev->start + prev->length;
876 if (*data == NULL)
877 next_start = region->start + region->length;
878 else
879 next_start = (*data)->start;
881 g_assert (prev_end <= next_start);
883 max_len = next_start - prev_end;
884 if (max_len < 128) {
885 if (++num_retries >= 10)
886 return NULL;
887 goto restart;
889 if (max_len > 1024)
890 max_len = 1024;
892 d = g_new0 (JitInfoData, 1);
893 d->start = prev_end + random () % (max_len / 2);
894 d->length = random () % MIN (max_len, next_start - d->start) + 1;
896 g_assert (d->start >= prev_end && d->start + d->length <= next_start);
898 d->ji = g_new0 (MonoJitInfo, 1);
899 d->ji->d.method = (MonoMethod*) 0xABadBabe;
900 d->ji->code_start = (gpointer)(gulong) d->start;
901 d->ji->code_size = d->length;
902 d->ji->cas_inited = 1; /* marks an allocated jit info */
904 d->next = *data;
905 *data = d;
907 ++region->num_datas;
909 return d;
912 static JitInfoData**
913 choose_random_data (Region *region)
915 int n;
916 int i;
917 JitInfoData **d;
919 g_assert (region->num_datas > 0);
921 n = random () % region->num_datas;
923 for (d = &region->data, i = 0;
924 i < n;
925 d = &(*d)->next, ++i)
928 return d;
931 static Region*
932 choose_random_region (ThreadData *td)
934 return &td->regions [random () % td->num_regions];
937 static ThreadData*
938 choose_random_thread (void)
940 return &thread_datas [random () % num_threads];
943 static void
944 free_jit_info_data (ThreadData *td, JitInfoData *free)
946 free->next = td->frees;
947 td->frees = free;
949 if (++td->num_frees >= 1000) {
950 int i;
952 for (i = 0; i < 500; ++i)
953 free = free->next;
955 while (free->next != NULL) {
956 JitInfoData *next = free->next->next;
958 //g_free (free->next->ji);
959 g_free (free->next);
960 free->next = next;
962 --td->num_frees;
967 #define NUM_THREADS 8
968 #define REGIONS_PER_THREAD 10
969 #define REGION_SIZE 0x10000
971 #define MAX_ADDR (REGION_SIZE * REGIONS_PER_THREAD * NUM_THREADS)
973 #define MODE_ALLOC 1
974 #define MODE_FREE 2
976 static void
977 test_thread_func (gpointer void_arg)
979 ThreadData* td = (ThreadData*)void_arg;
980 int mode = MODE_ALLOC;
981 int i = 0;
982 gulong lookup_successes = 0, lookup_failures = 0;
983 MonoDomain *domain = test_domain;
984 int thread_num = (int)(td - thread_datas);
985 gboolean modify_thread = thread_num < NUM_THREADS / 2; /* only half of the threads modify the table */
987 for (;;) {
988 int alloc;
989 int lookup = 1;
991 if (td->num_datas == 0) {
992 lookup = 0;
993 alloc = 1;
994 } else if (modify_thread && random () % 1000 < 5) {
995 lookup = 0;
996 if (mode == MODE_ALLOC)
997 alloc = (random () % 100) < 70;
998 else if (mode == MODE_FREE)
999 alloc = (random () % 100) < 30;
1002 if (lookup) {
1003 /* modify threads sometimes look up their own jit infos */
1004 if (modify_thread && random () % 10 < 5) {
1005 Region *region = choose_random_region (td);
1007 if (region->num_datas > 0) {
1008 JitInfoData **data = choose_random_data (region);
1009 guint pos = (*data)->start + random () % (*data)->length;
1010 MonoJitInfo *ji;
1012 ji = mono_jit_info_table_find (domain, (char*)(gsize)pos);
1014 g_assert (ji->cas_inited);
1015 g_assert ((*data)->ji == ji);
1017 } else {
1018 int pos = random () % MAX_ADDR;
1019 char *addr = (char*)(uintptr_t)pos;
1020 MonoJitInfo *ji;
1022 ji = mono_jit_info_table_find (domain, addr);
1025 * FIXME: We are actually not allowed
1026 * to do this. By the time we examine
1027 * the ji another thread might already
1028 * have removed it.
1030 if (ji != NULL) {
1031 g_assert (addr >= (char*)ji->code_start && addr < (char*)ji->code_start + ji->code_size);
1032 ++lookup_successes;
1033 } else
1034 ++lookup_failures;
1036 } else if (alloc) {
1037 JitInfoData *data = alloc_random_data (choose_random_region (td));
1039 if (data != NULL) {
1040 mono_jit_info_table_add (domain, data->ji);
1042 ++td->num_datas;
1044 } else {
1045 Region *region = choose_random_region (td);
1047 if (region->num_datas > 0) {
1048 JitInfoData **data = choose_random_data (region);
1049 JitInfoData *free;
1051 mono_jit_info_table_remove (domain, (*data)->ji);
1053 //(*data)->ji->cas_inited = 0; /* marks a free jit info */
1055 free = *data;
1056 *data = (*data)->next;
1058 free_jit_info_data (td, free);
1060 --region->num_datas;
1061 --td->num_datas;
1065 if (++i % 100000 == 0) {
1066 int j;
1067 g_print ("num datas %d (%ld - %ld): %d", (int)(td - thread_datas),
1068 lookup_successes, lookup_failures, td->num_datas);
1069 for (j = 0; j < td->num_regions; ++j)
1070 g_print (" %d", td->regions [j].num_datas);
1071 g_print ("\n");
1074 if (td->num_datas < 100)
1075 mode = MODE_ALLOC;
1076 else if (td->num_datas > 2000)
1077 mode = MODE_FREE;
1082 static void
1083 small_id_thread_func (gpointer arg)
1085 MonoThread *thread = mono_thread_current ();
1086 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1088 g_print ("my small id is %d\n", (int)thread->small_id);
1089 mono_hazard_pointer_clear (hp, 1);
1090 sleep (3);
1091 g_print ("done %d\n", (int)thread->small_id);
1095 static void
1096 jit_info_table_test (MonoDomain *domain)
1098 ERROR_DECL (error);
1099 int i;
1101 g_print ("testing jit_info_table\n");
1103 num_threads = NUM_THREADS;
1104 thread_datas = g_new0 (ThreadData, num_threads);
1106 for (i = 0; i < num_threads; ++i) {
1107 int j;
1109 thread_datas [i].num_regions = REGIONS_PER_THREAD;
1110 thread_datas [i].regions = g_new0 (Region, REGIONS_PER_THREAD);
1112 for (j = 0; j < REGIONS_PER_THREAD; ++j) {
1113 thread_datas [i].regions [j].start = (num_threads * j + i) * REGION_SIZE;
1114 thread_datas [i].regions [j].length = REGION_SIZE;
1118 test_domain = domain;
1121 for (i = 0; i < 72; ++i)
1122 mono_thread_create (domain, small_id_thread_func, NULL);
1124 sleep (2);
1127 for (i = 0; i < num_threads; ++i) {
1128 mono_thread_create_checked (domain, (gpointer)test_thread_func, &thread_datas [i], error);
1129 mono_error_assert_ok (error);
1132 #endif
1134 enum {
1135 DO_BENCH,
1136 DO_REGRESSION,
1137 DO_SINGLE_METHOD_REGRESSION,
1138 DO_COMPILE,
1139 DO_EXEC,
1140 DO_DRAW,
1141 DO_DEBUGGER
1144 typedef struct CompileAllThreadArgs {
1145 MonoAssembly *ass;
1146 int verbose;
1147 guint32 opts;
1148 guint32 recompilation_times;
1149 } CompileAllThreadArgs;
1151 static void
1152 compile_all_methods_thread_main_inner (CompileAllThreadArgs *args)
1154 MonoAssembly *ass = args->ass;
1155 int verbose = args->verbose;
1156 MonoImage *image = mono_assembly_get_image_internal (ass);
1157 MonoMethod *method;
1158 MonoCompile *cfg;
1159 int i, count = 0, fail_count = 0;
1161 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
1162 ERROR_DECL (error);
1163 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1164 MonoMethodSignature *sig;
1166 if (mono_metadata_has_generic_params (image, token))
1167 continue;
1169 method = mono_get_method_checked (image, token, NULL, NULL, error);
1170 if (!method) {
1171 mono_error_cleanup (error); /* FIXME don't swallow the error */
1172 continue;
1174 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1175 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1176 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1177 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1178 continue;
1180 if (mono_class_is_gtd (method->klass))
1181 continue;
1182 sig = mono_method_signature_internal (method);
1183 if (!sig) {
1184 char * desc = mono_method_full_name (method, TRUE);
1185 g_print ("Could not retrieve method signature for %s\n", desc);
1186 g_free (desc);
1187 fail_count ++;
1188 continue;
1191 if (sig->has_type_parameters)
1192 continue;
1194 count++;
1195 if (verbose) {
1196 char * desc = mono_method_full_name (method, TRUE);
1197 g_print ("Compiling %d %s\n", count, desc);
1198 g_free (desc);
1200 cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, args->opts), mono_get_root_domain (), (JitFlags)JIT_FLAG_DISCARD_RESULTS, 0, -1);
1201 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
1202 const char *msg = cfg->exception_message;
1203 if (cfg->exception_type == MONO_EXCEPTION_MONO_ERROR)
1204 msg = mono_error_get_message (&cfg->error);
1205 g_print ("Compilation of %s failed with exception '%s':\n", mono_method_full_name (cfg->method, TRUE), msg);
1206 fail_count ++;
1208 mono_destroy_compile (cfg);
1211 if (fail_count)
1212 exit (1);
1215 static void
1216 compile_all_methods_thread_main (gpointer void_args)
1218 CompileAllThreadArgs *args = (CompileAllThreadArgs*)void_args;
1219 guint32 i;
1220 for (i = 0; i < args->recompilation_times; ++i)
1221 compile_all_methods_thread_main_inner (args);
1224 static void
1225 compile_all_methods (MonoAssembly *ass, int verbose, guint32 opts, guint32 recompilation_times)
1227 ERROR_DECL (error);
1228 CompileAllThreadArgs args;
1230 args.ass = ass;
1231 args.verbose = verbose;
1232 args.opts = opts;
1233 args.recompilation_times = recompilation_times;
1236 * Need to create a mono thread since compilation might trigger
1237 * running of managed code.
1239 mono_thread_create_checked (mono_domain_get (), (gpointer)compile_all_methods_thread_main, &args, error);
1240 mono_error_assert_ok (error);
1242 mono_thread_manage ();
1246 * mono_jit_exec:
1247 * \param assembly reference to an assembly
1248 * \param argc argument count
1249 * \param argv argument vector
1250 * Start execution of a program.
1252 int
1253 mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
1255 int rv;
1256 MONO_ENTER_GC_UNSAFE;
1257 rv = mono_jit_exec_internal (domain, assembly, argc, argv);
1258 MONO_EXIT_GC_UNSAFE;
1259 return rv;
1263 mono_jit_exec_internal (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
1265 MONO_REQ_GC_UNSAFE_MODE;
1266 ERROR_DECL (error);
1267 MonoImage *image = mono_assembly_get_image_internal (assembly);
1268 MonoMethod *method;
1269 guint32 entry = mono_image_get_entry_point (image);
1271 if (!entry) {
1272 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
1273 /* FIXME: remove this silly requirement. */
1274 mono_environment_exitcode_set (1);
1275 return 1;
1278 method = mono_get_method_checked (image, entry, NULL, NULL, error);
1279 if (method == NULL){
1280 g_print ("The entry point method could not be loaded due to %s\n", mono_error_get_message (error));
1281 mono_error_cleanup (error);
1282 mono_environment_exitcode_set (1);
1283 return 1;
1286 if (mono_llvm_only) {
1287 MonoObject *exc = NULL;
1288 int res;
1290 res = mono_runtime_try_run_main (method, argc, argv, &exc);
1291 if (exc) {
1292 mono_unhandled_exception_internal (exc);
1293 mono_invoke_unhandled_exception_hook (exc);
1294 g_assert_not_reached ();
1296 return res;
1297 } else {
1298 int res = mono_runtime_run_main_checked (method, argc, argv, error);
1299 if (!is_ok (error)) {
1300 MonoException *ex = mono_error_convert_to_exception (error);
1301 if (ex) {
1302 mono_unhandled_exception_internal (&ex->object);
1303 mono_invoke_unhandled_exception_hook (&ex->object);
1304 g_assert_not_reached ();
1307 return res;
1311 typedef struct
1313 MonoDomain *domain;
1314 const char *file;
1315 int argc;
1316 char **argv;
1317 guint32 opts;
1318 char *aot_options;
1319 } MainThreadArgs;
1321 static void main_thread_handler (gpointer user_data)
1323 MainThreadArgs *main_args = (MainThreadArgs *)user_data;
1324 MonoAssembly *assembly;
1326 if (mono_compile_aot) {
1327 int i, res;
1328 gpointer *aot_state = NULL;
1330 /* Treat the other arguments as assemblies to compile too */
1331 for (i = 0; i < main_args->argc; ++i) {
1332 assembly = mono_domain_assembly_open (main_args->domain, main_args->argv [i]);
1333 if (!assembly) {
1334 fprintf (stderr, "Can not open image %s\n", main_args->argv [i]);
1335 exit (1);
1337 /* Check that the assembly loaded matches the filename */
1339 MonoImageOpenStatus status;
1340 MonoImage *img;
1342 img = mono_image_open (main_args->argv [i], &status);
1343 if (img && strcmp (img->name, assembly->image->name)) {
1344 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);
1345 exit (1);
1348 res = mono_compile_assembly (assembly, main_args->opts, main_args->aot_options, &aot_state);
1349 if (res != 0) {
1350 fprintf (stderr, "AOT of image %s failed.\n", main_args->argv [i]);
1351 exit (1);
1354 if (aot_state) {
1355 res = mono_compile_deferred_assemblies (main_args->opts, main_args->aot_options, &aot_state);
1356 if (res != 0) {
1357 fprintf (stderr, "AOT of mode-specific deferred assemblies failed.\n");
1358 exit (1);
1361 } else {
1362 assembly = mono_domain_assembly_open (main_args->domain, main_args->file);
1363 if (!assembly){
1364 fprintf (stderr, "Can not open image %s\n", main_args->file);
1365 exit (1);
1369 * This must be done in a thread managed by mono since it can invoke
1370 * managed code.
1372 if (main_args->opts & MONO_OPT_PRECOMP)
1373 mono_precompile_assemblies ();
1375 mono_jit_exec (main_args->domain, assembly, main_args->argc, main_args->argv);
1379 static int
1380 load_agent (MonoDomain *domain, char *desc)
1382 ERROR_DECL (error);
1383 char* col = strchr (desc, ':');
1384 char *agent, *args;
1385 MonoAssembly *agent_assembly;
1386 MonoImage *image;
1387 MonoMethod *method;
1388 guint32 entry;
1389 MonoArray *main_args;
1390 gpointer pa [1];
1391 MonoImageOpenStatus open_status;
1393 if (col) {
1394 agent = (char *)g_memdup (desc, col - desc + 1);
1395 agent [col - desc] = '\0';
1396 args = col + 1;
1397 } else {
1398 agent = g_strdup (desc);
1399 args = NULL;
1402 MonoAssemblyOpenRequest req;
1403 mono_assembly_request_prepare (&req.request, sizeof (req), MONO_ASMCTX_DEFAULT);
1404 agent_assembly = mono_assembly_request_open (agent, &req, &open_status);
1405 if (!agent_assembly) {
1406 fprintf (stderr, "Cannot open agent assembly '%s': %s.\n", agent, mono_image_strerror (open_status));
1407 g_free (agent);
1408 return 2;
1412 * Can't use mono_jit_exec (), as it sets things which might confuse the
1413 * real Main method.
1415 image = mono_assembly_get_image_internal (agent_assembly);
1416 entry = mono_image_get_entry_point (image);
1417 if (!entry) {
1418 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
1419 g_free (agent);
1420 return 1;
1423 method = mono_get_method_checked (image, entry, NULL, NULL, error);
1424 if (method == NULL){
1425 g_print ("The entry point method of assembly '%s' could not be loaded due to %s\n", agent, mono_error_get_message (error));
1426 mono_error_cleanup (error);
1427 g_free (agent);
1428 return 1;
1431 mono_thread_set_main (mono_thread_current ());
1433 if (args) {
1434 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 1, error);
1435 if (main_args) {
1436 MonoString *str = mono_string_new_checked (domain, args, error);
1437 if (str)
1438 mono_array_set_internal (main_args, MonoString*, 0, str);
1440 } else {
1441 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 0, error);
1443 if (!main_args) {
1444 g_print ("Could not allocate array for main args of assembly '%s' due to %s\n", agent, mono_error_get_message (error));
1445 mono_error_cleanup (error);
1446 g_free (agent);
1447 return 1;
1451 pa [0] = main_args;
1452 /* Pass NULL as 'exc' so unhandled exceptions abort the runtime */
1453 mono_runtime_invoke_checked (method, NULL, pa, error);
1454 if (!is_ok (error)) {
1455 g_print ("The entry point method of assembly '%s' could not execute due to %s\n", agent, mono_error_get_message (error));
1456 mono_error_cleanup (error);
1457 g_free (agent);
1458 return 1;
1461 g_free (agent);
1462 return 0;
1465 static void
1466 mini_usage_jitdeveloper (void)
1468 int i;
1470 fprintf (stdout,
1471 "Runtime and JIT debugging options:\n"
1472 " --apply-bindings=FILE Apply assembly bindings from FILE (only for AOT)\n"
1473 " --breakonex Inserts a breakpoint on exceptions\n"
1474 " --break METHOD Inserts a breakpoint at METHOD entry\n"
1475 " --break-at-bb METHOD N Inserts a breakpoint in METHOD at BB N\n"
1476 " --compile METHOD Just compile METHOD in assembly\n"
1477 " --compile-all=N Compiles all the methods in the assembly multiple times (default: 1)\n"
1478 " --ncompile N Number of times to compile METHOD (default: 1)\n"
1479 " --print-vtable Print the vtable of all used classes\n"
1480 " --regression Runs the regression test contained in the assembly\n"
1481 " --single-method=OPTS Runs regressions with only one method optimized with OPTS at any time\n"
1482 " --statfile FILE Sets the stat file to FILE\n"
1483 " --stats Print statistics about the JIT operations\n"
1484 " --inject-async-exc METHOD OFFSET Inject an asynchronous exception at METHOD\n"
1485 " --verify-all Run the verifier on all assemblies and methods\n"
1486 " --full-aot Avoid JITting any code\n"
1487 " --llvmonly Use LLVM compiled code only\n"
1488 " --agent=ASSEMBLY[:ARG] Loads the specific agent assembly and executes its Main method with the given argument before loading the main assembly.\n"
1489 " --no-x86-stack-align Don't align stack on x86\n"
1490 "\n"
1491 "The options supported by MONO_DEBUG can also be passed on the command line.\n"
1492 "\n"
1493 "Other options:\n"
1494 " --graph[=TYPE] METHOD Draws a graph of the specified method:\n");
1496 for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
1497 fprintf (stdout, " %-10s %s\n", graph_names [i].name, graph_names [i].desc);
1501 static void
1502 mini_usage_list_opt (void)
1504 int i;
1506 for (i = 0; i < G_N_ELEMENTS (opt_names); ++i)
1507 fprintf (stdout, " %-10s %s\n", optflag_get_name (i), optflag_get_desc (i));
1510 static void
1511 mini_usage (void)
1513 fprintf (stdout,
1514 "Usage is: mono [options] program [program-options]\n"
1515 "\n"
1516 "Development:\n"
1517 " --aot[=<options>] Compiles the assembly to native code\n"
1518 " --debug[=<options>] Enable debugging support, use --help-debug for details\n"
1519 " --debugger-agent=options Enable the debugger agent\n"
1520 " --profile[=profiler] Runs in profiling mode with the specified profiler module\n"
1521 " --trace[=EXPR] Enable tracing, use --help-trace for details\n"
1522 " --jitmap Output a jit method map to /tmp/perf-PID.map\n"
1523 " --help-devel Shows more options available to developers\n"
1524 "\n"
1525 "Runtime:\n"
1526 " --config FILE Loads FILE as the Mono config\n"
1527 " --verbose, -v Increases the verbosity level\n"
1528 " --help, -h Show usage information\n"
1529 " --version, -V Show version information\n"
1530 " --runtime=VERSION Use the VERSION runtime, instead of autodetecting\n"
1531 " --optimize=OPT Turns on or off a specific optimization\n"
1532 " Use --list-opt to get a list of optimizations\n"
1533 #ifndef DISABLE_SECURITY
1534 " --security[=mode] Turns on the unsupported security manager (off by default)\n"
1535 " mode is one of cas, core-clr, verifiable or validil\n"
1536 #endif
1537 " --attach=OPTIONS Pass OPTIONS to the attach agent in the runtime.\n"
1538 " Currently the only supported option is 'disable'.\n"
1539 " --llvm, --nollvm Controls whenever the runtime uses LLVM to compile code.\n"
1540 " --gc=[sgen,boehm] Select SGen or Boehm GC (runs mono or mono-sgen)\n"
1541 #ifdef TARGET_OSX
1542 " --arch=[32,64] Select architecture (runs mono32 or mono64)\n"
1543 #endif
1544 #ifdef HOST_WIN32
1545 " --mixed-mode Enable mixed-mode image support.\n"
1546 #endif
1547 " --handlers Install custom handlers, use --help-handlers for details.\n"
1548 " --aot-path=PATH List of additional directories to search for AOT images.\n"
1552 static void
1553 mini_trace_usage (void)
1555 fprintf (stdout,
1556 "Tracing options:\n"
1557 " --trace[=EXPR] Trace every call, optional EXPR controls the scope\n"
1558 "\n"
1559 "EXPR is composed of:\n"
1560 " all All assemblies\n"
1561 " none No assemblies\n"
1562 " program Entry point assembly\n"
1563 " assembly Specifies an assembly\n"
1564 " wrapper All wrappers bridging native and managed code\n"
1565 " M:Type:Method Specifies a method\n"
1566 " N:Namespace Specifies a namespace\n"
1567 " T:Type Specifies a type\n"
1568 " E:Type Specifies stack traces for an exception type\n"
1569 " EXPR Includes expression\n"
1570 " -EXPR Excludes expression\n"
1571 " EXPR,EXPR Multiple expressions\n"
1572 " disabled Don't print any output until toggled via SIGUSR2\n");
1575 static void
1576 mini_debug_usage (void)
1578 fprintf (stdout,
1579 "Debugging options:\n"
1580 " --debug[=OPTIONS] Enable debugging support, optional OPTIONS is a comma\n"
1581 " separated list of options\n"
1582 "\n"
1583 "OPTIONS is composed of:\n"
1584 " casts Enable more detailed InvalidCastException messages.\n"
1585 " mdb-optimizations Disable some JIT optimizations which are normally\n"
1586 " disabled when running inside the debugger.\n"
1587 " This is useful if you plan to attach to the running\n"
1588 " process with the debugger.\n");
1591 #if defined(MONO_ARCH_ARCHITECTURE)
1592 /* Redefine MONO_ARCHITECTURE to include more information */
1593 #undef MONO_ARCHITECTURE
1594 #define MONO_ARCHITECTURE MONO_ARCH_ARCHITECTURE
1595 #endif
1597 static char *
1598 mono_get_version_info (void)
1600 GString *output;
1601 output = g_string_new ("");
1603 #ifdef MONO_KEYWORD_THREAD
1604 g_string_append_printf (output, "\tTLS: __thread\n");
1605 #else
1606 g_string_append_printf (output, "\tTLS: \n");
1607 #endif /* MONO_KEYWORD_THREAD */
1609 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
1610 g_string_append_printf (output, "\tSIGSEGV: altstack\n");
1611 #else
1612 g_string_append_printf (output, "\tSIGSEGV: normal\n");
1613 #endif
1615 #ifdef HAVE_EPOLL
1616 g_string_append_printf (output, "\tNotifications: epoll\n");
1617 #elif defined(HAVE_KQUEUE)
1618 g_string_append_printf (output, "\tNotification: kqueue\n");
1619 #else
1620 g_string_append_printf (output, "\tNotification: Thread + polling\n");
1621 #endif
1623 g_string_append_printf (output, "\tArchitecture: %s\n", MONO_ARCHITECTURE);
1624 g_string_append_printf (output, "\tDisabled: %s\n", DISABLED_FEATURES);
1626 g_string_append_printf (output, "\tMisc: ");
1627 #ifdef MONO_SMALL_CONFIG
1628 g_string_append_printf (output, "smallconfig ");
1629 #endif
1631 #ifdef MONO_BIG_ARRAYS
1632 g_string_append_printf (output, "bigarrays ");
1633 #endif
1635 #if !defined(DISABLE_SDB)
1636 g_string_append_printf (output, "softdebug ");
1637 #endif
1638 g_string_append_printf (output, "\n");
1640 #ifndef DISABLE_INTERPRETER
1641 g_string_append_printf (output, "\tInterpreter: yes\n");
1642 #else
1643 g_string_append_printf (output, "\tInterpreter: no\n");
1644 #endif
1646 #ifdef MONO_ARCH_LLVM_SUPPORTED
1647 #ifdef ENABLE_LLVM
1648 g_string_append_printf (output, "\tLLVM: yes(%d)\n", LLVM_API_VERSION);
1649 #else
1650 g_string_append_printf (output, "\tLLVM: supported, not enabled.\n");
1651 #endif
1652 #endif
1654 g_string_append_printf (output, "\tSuspend: %s\n", mono_threads_suspend_policy_name ());
1656 return g_string_free (output, FALSE);
1659 #ifndef MONO_ARCH_AOT_SUPPORTED
1660 #define error_if_aot_unsupported() do {fprintf (stderr, "AOT compilation is not supported on this platform.\n"); exit (1);} while (0)
1661 #else
1662 #define error_if_aot_unsupported()
1663 #endif
1665 static gboolean enable_debugging;
1668 * mono_jit_parse_options:
1670 * Process the command line options in \p argv as done by the runtime executable.
1671 * This should be called before \c mono_jit_init.
1673 void
1674 mono_jit_parse_options (int argc, char * argv[])
1676 int i;
1677 char *trace_options = NULL;
1678 int mini_verbose = 0;
1679 guint32 opt;
1682 * Some options have no effect here, since they influence the behavior of
1683 * mono_main ().
1686 opt = mono_parse_default_optimizations (NULL);
1688 /* FIXME: Avoid code duplication */
1689 for (i = 0; i < argc; ++i) {
1690 if (argv [i] [0] != '-')
1691 break;
1692 if (strncmp (argv [i], "--debugger-agent=", 17) == 0) {
1693 MonoDebugOptions *opt = mini_get_debug_options ();
1695 sdb_options = g_strdup (argv [i] + 17);
1696 opt->mdb_optimizations = TRUE;
1697 enable_debugging = TRUE;
1698 } else if (!strcmp (argv [i], "--soft-breakpoints")) {
1699 MonoDebugOptions *opt = mini_get_debug_options ();
1701 opt->soft_breakpoints = TRUE;
1702 opt->explicit_null_checks = TRUE;
1703 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
1704 opt = parse_optimizations (opt, argv [i] + 11, TRUE);
1705 mono_set_optimizations (opt);
1706 } else if (strncmp (argv [i], "-O=", 3) == 0) {
1707 opt = parse_optimizations (opt, argv [i] + 3, TRUE);
1708 mono_set_optimizations (opt);
1709 } else if (strcmp (argv [i], "--trace") == 0) {
1710 trace_options = (char*)"";
1711 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
1712 trace_options = &argv [i][8];
1713 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
1714 mini_verbose++;
1715 } else if (strcmp (argv [i], "--breakonex") == 0) {
1716 MonoDebugOptions *opt = mini_get_debug_options ();
1718 opt->break_on_exc = TRUE;
1719 } else if (strcmp (argv [i], "--stats") == 0) {
1720 mono_counters_enable (-1);
1721 mono_atomic_store_bool (&mono_stats.enabled, TRUE);
1722 mono_atomic_store_bool (&mono_jit_stats.enabled, TRUE);
1723 } else if (strcmp (argv [i], "--break") == 0) {
1724 if (i+1 >= argc){
1725 fprintf (stderr, "Missing method name in --break command line option\n");
1726 exit (1);
1729 if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
1730 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
1731 } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
1732 mono_gc_params_set (argv[i] + 12);
1733 } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
1734 mono_gc_debug_set (argv[i] + 11);
1735 } else if (strcmp (argv [i], "--llvm") == 0) {
1736 #ifndef MONO_ARCH_LLVM_SUPPORTED
1737 fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
1738 #elif !defined(ENABLE_LLVM)
1739 fprintf (stderr, "Mono Warning: --llvm not enabled in this runtime.\n");
1740 #else
1741 mono_use_llvm = TRUE;
1742 #endif
1743 } else if (argv [i][0] == '-' && argv [i][1] == '-' && mini_parse_debug_option (argv [i] + 2)) {
1744 } else {
1745 fprintf (stderr, "Unsupported command line option: '%s'\n", argv [i]);
1746 exit (1);
1750 if (trace_options != NULL) {
1752 * Need to call this before mini_init () so we can trace methods
1753 * compiled there too.
1755 mono_jit_trace_calls = mono_trace_set_options (trace_options);
1756 if (mono_jit_trace_calls == NULL)
1757 exit (1);
1760 if (mini_verbose)
1761 mono_set_verbose_level (mini_verbose);
1764 static void
1765 mono_set_use_smp (int use_smp)
1767 #if HAVE_SCHED_SETAFFINITY
1768 if (!use_smp) {
1769 unsigned long proc_mask = 1;
1770 #ifdef GLIBC_BEFORE_2_3_4_SCHED_SETAFFINITY
1771 sched_setaffinity (getpid(), (gpointer)&proc_mask);
1772 #else
1773 sched_setaffinity (getpid(), sizeof (unsigned long), (const cpu_set_t *)&proc_mask);
1774 #endif
1776 #endif
1779 static void
1780 switch_gc (char* argv[], const char* target_gc)
1782 GString *path;
1784 if (!strcmp (mono_gc_get_gc_name (), target_gc)) {
1785 return;
1788 path = g_string_new (argv [0]);
1790 /*Running mono without any argument*/
1791 if (strstr (argv [0], "-sgen"))
1792 g_string_truncate (path, path->len - 5);
1793 else if (strstr (argv [0], "-boehm"))
1794 g_string_truncate (path, path->len - 6);
1796 g_string_append_c (path, '-');
1797 g_string_append (path, target_gc);
1799 #ifdef HAVE_EXECVP
1800 execvp (path->str, argv);
1801 fprintf (stderr, "Error: Failed to switch to %s gc. mono-%s is not installed.\n", target_gc, target_gc);
1802 #else
1803 fprintf (stderr, "Error: --gc=<NAME> option not supported on this platform.\n");
1804 #endif
1807 #ifdef TARGET_OSX
1810 * tries to increase the minimum number of files, if the number is below 1024
1812 static void
1813 darwin_change_default_file_handles ()
1815 struct rlimit limit;
1817 if (getrlimit (RLIMIT_NOFILE, &limit) == 0){
1818 if (limit.rlim_cur < 1024){
1819 limit.rlim_cur = MAX(1024,limit.rlim_cur);
1820 setrlimit (RLIMIT_NOFILE, &limit);
1825 static void
1826 switch_arch (char* argv[], const char* target_arch)
1828 GString *path;
1829 gsize arch_offset;
1831 if ((strcmp (target_arch, "32") == 0 && strcmp (MONO_ARCHITECTURE, "x86") == 0) ||
1832 (strcmp (target_arch, "64") == 0 && strcmp (MONO_ARCHITECTURE, "amd64") == 0)) {
1833 return; /* matching arch loaded */
1836 path = g_string_new (argv [0]);
1837 arch_offset = path->len -2; /* last two characters */
1839 /* Remove arch suffix if present */
1840 if (strstr (&path->str[arch_offset], "32") || strstr (&path->str[arch_offset], "64")) {
1841 g_string_truncate (path, arch_offset);
1844 g_string_append (path, target_arch);
1846 if (execvp (path->str, argv) < 0) {
1847 fprintf (stderr, "Error: --arch=%s Failed to switch to '%s'.\n", target_arch, path->str);
1848 exit (1);
1852 #endif
1854 #define MONO_HANDLERS_ARGUMENT "--handlers="
1855 #define MONO_HANDLERS_ARGUMENT_LEN G_N_ELEMENTS(MONO_HANDLERS_ARGUMENT)-1
1857 static void
1858 apply_root_domain_configuration_file_bindings (MonoDomain *domain, char *root_domain_configuration_file)
1860 g_assert (domain->setup == NULL || domain->setup->configuration_file == NULL);
1861 g_assert (!domain->assembly_bindings_parsed);
1863 mono_domain_parse_assembly_bindings (domain, 0, 0, root_domain_configuration_file);
1867 static void
1868 mono_enable_interp (const char *opts)
1870 mono_runtime_set_execution_mode (MONO_EE_MODE_INTERP);
1871 if (opts)
1872 mono_interp_opts_string = opts;
1874 #ifdef DISABLE_INTERPRETER
1875 g_error ("Mono IL interpreter support is missing\n");
1876 #endif
1878 #ifdef MONO_CROSS_COMPILE
1879 g_error ("--interpreter on cross-compile runtimes not supported\n");
1880 #endif
1882 #ifndef MONO_ARCH_INTERPRETER_SUPPORTED
1883 g_error ("--interpreter not supported on this architecture.\n");
1884 #endif
1888 static int
1889 mono_exec_regression_internal (int verbose_level, int count, char *images [], gboolean single_method)
1891 mono_do_single_method_regression = single_method;
1892 if (mono_use_interpreter) {
1893 if (mono_interp_regression_list (verbose_level, count, images)) {
1894 g_print ("Regression ERRORS!\n");
1895 return 1;
1897 return 0;
1899 if (mini_regression_list (verbose_level, count, images)) {
1900 g_print ("Regression ERRORS!\n");
1901 return 1;
1903 return 0;
1908 * Returns TRUE for success, FALSE for failure.
1910 gboolean
1911 mono_regression_test_step (int verbose_level, const char *image, const char *method_name)
1913 if (method_name) {
1914 //TODO
1915 } else {
1916 do_regression_retries = TRUE;
1919 char *images[] = {
1920 (char*)image,
1921 NULL
1924 return mono_exec_regression_internal (verbose_level, 1, images, FALSE) == 0;
1927 * mono_main:
1928 * \param argc number of arguments in the argv array
1929 * \param argv array of strings containing the startup arguments
1930 * Launches the Mono JIT engine and parses all the command line options
1931 * in the same way that the mono command line VM would.
1934 mono_main (int argc, char* argv[])
1936 MainThreadArgs main_args;
1937 MonoAssembly *assembly;
1938 MonoMethodDesc *desc;
1939 MonoMethod *method;
1940 MonoCompile *cfg;
1941 MonoDomain *domain;
1942 MonoImageOpenStatus open_status;
1943 const char* aname, *mname = NULL;
1944 char *config_file = NULL;
1945 int i, count = 1;
1946 guint32 opt, action = DO_EXEC, recompilation_times = 1;
1947 MonoGraphOptions mono_graph_options = (MonoGraphOptions)0;
1948 int mini_verbose = 0;
1949 char *trace_options = NULL;
1950 char *aot_options = NULL;
1951 char *forced_version = NULL;
1952 GPtrArray *agents = NULL;
1953 char *attach_options = NULL;
1954 char *extra_bindings_config_file = NULL;
1955 #ifdef MONO_JIT_INFO_TABLE_TEST
1956 int test_jit_info_table = FALSE;
1957 #endif
1958 #ifdef HOST_WIN32
1959 int mixed_mode = FALSE;
1960 #endif
1962 #ifdef MOONLIGHT
1963 #ifndef HOST_WIN32
1964 /* stdout defaults to block buffering if it's not writing to a terminal, which
1965 * happens with our test harness: we redirect stdout to capture it. Force line
1966 * buffering in all cases. */
1967 setlinebuf (stdout);
1968 #endif
1969 #endif
1971 setlocale (LC_ALL, "");
1973 #if TARGET_OSX
1974 darwin_change_default_file_handles ();
1975 #endif
1977 if (g_hasenv ("MONO_NO_SMP"))
1978 mono_set_use_smp (FALSE);
1980 #ifdef MONO_JEMALLOC_ENABLED
1982 gboolean use_jemalloc = FALSE;
1983 #ifdef MONO_JEMALLOC_DEFAULT
1984 use_jemalloc = TRUE;
1985 #endif
1986 if (!use_jemalloc)
1987 use_jemalloc = g_hasenv ("MONO_USE_JEMALLOC");
1989 if (use_jemalloc)
1990 mono_init_jemalloc ();
1992 #endif
1994 g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
1995 g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
1997 opt = mono_parse_default_optimizations (NULL);
1999 for (i = 1; i < argc; ++i) {
2000 if (argv [i] [0] != '-')
2001 break;
2002 if (strcmp (argv [i], "--regression") == 0) {
2003 action = DO_REGRESSION;
2004 } else if (strncmp (argv [i], "--single-method=", 16) == 0) {
2005 char *full_opts = g_strdup_printf ("-all,%s", argv [i] + 16);
2006 action = DO_SINGLE_METHOD_REGRESSION;
2007 mono_single_method_regression_opt = parse_optimizations (opt, full_opts, TRUE);
2008 g_free (full_opts);
2009 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
2010 mini_verbose++;
2011 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
2012 char *build = mono_get_runtime_build_info ();
2013 char *gc_descr;
2015 g_print ("Mono JIT compiler version %s\nCopyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com\n", build);
2016 g_free (build);
2017 char *info = mono_get_version_info ();
2018 g_print (info);
2019 g_free (info);
2021 gc_descr = mono_gc_get_description ();
2022 g_print ("\tGC: %s\n", gc_descr);
2023 g_free (gc_descr);
2024 return 0;
2025 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
2026 mini_usage ();
2027 return 0;
2028 } else if (strcmp (argv [i], "--help-trace") == 0){
2029 mini_trace_usage ();
2030 return 0;
2031 } else if (strcmp (argv [i], "--help-devel") == 0){
2032 mini_usage_jitdeveloper ();
2033 return 0;
2034 } else if (strcmp (argv [i], "--help-debug") == 0){
2035 mini_debug_usage ();
2036 return 0;
2037 } else if (strcmp (argv [i], "--list-opt") == 0){
2038 mini_usage_list_opt ();
2039 return 0;
2040 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
2041 if (i + 1 >= argc){
2042 fprintf (stderr, "error: --statfile requires a filename argument\n");
2043 return 1;
2045 mini_stats_fd = fopen (argv [++i], "w+");
2046 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
2047 opt = parse_optimizations (opt, argv [i] + 11, TRUE);
2048 } else if (strncmp (argv [i], "-O=", 3) == 0) {
2049 opt = parse_optimizations (opt, argv [i] + 3, TRUE);
2050 } else if (strncmp (argv [i], "--bisect=", 9) == 0) {
2051 char *param = argv [i] + 9;
2052 char *sep = strchr (param, ':');
2053 if (!sep) {
2054 fprintf (stderr, "Error: --bisect requires OPT:FILENAME\n");
2055 return 1;
2057 char *opt_string = g_strndup (param, sep - param);
2058 guint32 opt = parse_optimizations (0, opt_string, FALSE);
2059 g_free (opt_string);
2060 mono_set_bisect_methods (opt, sep + 1);
2061 } else if (strcmp (argv [i], "--gc=sgen") == 0) {
2062 switch_gc (argv, "sgen");
2063 } else if (strcmp (argv [i], "--gc=boehm") == 0) {
2064 switch_gc (argv, "boehm");
2065 } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
2066 mono_gc_params_set (argv[i] + 12);
2067 } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
2068 mono_gc_debug_set (argv[i] + 11);
2070 #ifdef TARGET_OSX
2071 else if (strcmp (argv [i], "--arch=32") == 0) {
2072 switch_arch (argv, "32");
2073 } else if (strcmp (argv [i], "--arch=64") == 0) {
2074 switch_arch (argv, "64");
2076 #endif
2077 else if (strcmp (argv [i], "--config") == 0) {
2078 if (i +1 >= argc){
2079 fprintf (stderr, "error: --config requires a filename argument\n");
2080 return 1;
2082 config_file = argv [++i];
2083 #ifdef HOST_WIN32
2084 } else if (strcmp (argv [i], "--mixed-mode") == 0) {
2085 mixed_mode = TRUE;
2086 #endif
2087 } else if (strcmp (argv [i], "--ncompile") == 0) {
2088 if (i + 1 >= argc){
2089 fprintf (stderr, "error: --ncompile requires an argument\n");
2090 return 1;
2092 count = atoi (argv [++i]);
2093 action = DO_BENCH;
2094 } else if (strcmp (argv [i], "--trace") == 0) {
2095 trace_options = (char*)"";
2096 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
2097 trace_options = &argv [i][8];
2098 } else if (strcmp (argv [i], "--breakonex") == 0) {
2099 MonoDebugOptions *opt = mini_get_debug_options ();
2101 opt->break_on_exc = TRUE;
2102 } else if (strcmp (argv [i], "--break") == 0) {
2103 if (i+1 >= argc){
2104 fprintf (stderr, "Missing method name in --break command line option\n");
2105 return 1;
2108 if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
2109 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
2110 } else if (strcmp (argv [i], "--break-at-bb") == 0) {
2111 if (i + 2 >= argc) {
2112 fprintf (stderr, "Missing method name or bb num in --break-at-bb command line option.");
2113 return 1;
2115 mono_break_at_bb_method = mono_method_desc_new (argv [++i], TRUE);
2116 if (mono_break_at_bb_method == NULL) {
2117 fprintf (stderr, "Method name is in a bad format in --break-at-bb command line option.");
2118 return 1;
2120 mono_break_at_bb_bb_num = atoi (argv [++i]);
2121 } else if (strcmp (argv [i], "--inject-async-exc") == 0) {
2122 if (i + 2 >= argc) {
2123 fprintf (stderr, "Missing method name or position in --inject-async-exc command line option\n");
2124 return 1;
2126 mono_inject_async_exc_method = mono_method_desc_new (argv [++i], TRUE);
2127 if (mono_inject_async_exc_method == NULL) {
2128 fprintf (stderr, "Method name is in a bad format in --inject-async-exc command line option\n");
2129 return 1;
2131 mono_inject_async_exc_pos = atoi (argv [++i]);
2132 } else if (strcmp (argv [i], "--verify-all") == 0) {
2133 mono_verifier_enable_verify_all ();
2134 } else if (strcmp (argv [i], "--full-aot") == 0) {
2135 mono_jit_set_aot_mode (MONO_AOT_MODE_FULL);
2136 } else if (strcmp (argv [i], "--llvmonly") == 0) {
2137 mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY);
2138 } else if (strcmp (argv [i], "--hybrid-aot") == 0) {
2139 mono_jit_set_aot_mode (MONO_AOT_MODE_HYBRID);
2140 } else if (strcmp (argv [i], "--full-aot-interp") == 0) {
2141 mono_jit_set_aot_mode (MONO_AOT_MODE_INTERP);
2142 } else if (strcmp (argv [i], "--llvmonly-interp") == 0) {
2143 mono_jit_set_aot_mode (MONO_AOT_MODE_INTERP_LLVMONLY);
2144 } else if (strcmp (argv [i], "--print-vtable") == 0) {
2145 mono_print_vtable = TRUE;
2146 } else if (strcmp (argv [i], "--stats") == 0) {
2147 mono_counters_enable (-1);
2148 mono_atomic_store_bool (&mono_stats.enabled, TRUE);
2149 mono_atomic_store_bool (&mono_jit_stats.enabled, TRUE);
2150 #ifndef DISABLE_AOT
2151 } else if (strcmp (argv [i], "--aot") == 0) {
2152 error_if_aot_unsupported ();
2153 mono_compile_aot = TRUE;
2154 } else if (strncmp (argv [i], "--aot=", 6) == 0) {
2155 error_if_aot_unsupported ();
2156 mono_compile_aot = TRUE;
2157 if (aot_options) {
2158 char *tmp = g_strdup_printf ("%s,%s", aot_options, &argv [i][6]);
2159 g_free (aot_options);
2160 aot_options = tmp;
2161 } else {
2162 aot_options = g_strdup (&argv [i][6]);
2164 #endif
2165 } else if (strncmp (argv [i], "--apply-bindings=", 17) == 0) {
2166 extra_bindings_config_file = &argv[i][17];
2167 } else if (strncmp (argv [i], "--aot-path=", 11) == 0) {
2168 char **splitted;
2170 splitted = g_strsplit (argv [i] + 11, G_SEARCHPATH_SEPARATOR_S, 1000);
2171 while (*splitted) {
2172 char *tmp = *splitted;
2173 mono_aot_paths = g_list_append (mono_aot_paths, g_strdup (tmp));
2174 g_free (tmp);
2175 splitted++;
2177 } else if (strncmp (argv [i], "--compile-all=", 14) == 0) {
2178 action = DO_COMPILE;
2179 recompilation_times = atoi (argv [i] + 14);
2180 } else if (strcmp (argv [i], "--compile-all") == 0) {
2181 action = DO_COMPILE;
2182 } else if (strncmp (argv [i], "--runtime=", 10) == 0) {
2183 forced_version = &argv [i][10];
2184 } else if (strcmp (argv [i], "--jitmap") == 0) {
2185 mono_enable_jit_map ();
2186 } else if (strcmp (argv [i], "--profile") == 0) {
2187 mini_add_profiler_argument (NULL);
2188 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
2189 mini_add_profiler_argument (argv [i] + 10);
2190 } else if (strncmp (argv [i], "--agent=", 8) == 0) {
2191 if (agents == NULL)
2192 agents = g_ptr_array_new ();
2193 g_ptr_array_add (agents, argv [i] + 8);
2194 } else if (strncmp (argv [i], "--attach=", 9) == 0) {
2195 attach_options = argv [i] + 9;
2196 } else if (strcmp (argv [i], "--compile") == 0) {
2197 if (i + 1 >= argc){
2198 fprintf (stderr, "error: --compile option requires a method name argument\n");
2199 return 1;
2202 mname = argv [++i];
2203 action = DO_BENCH;
2204 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
2205 if (i + 1 >= argc){
2206 fprintf (stderr, "error: --graph option requires a method name argument\n");
2207 return 1;
2210 mono_graph_options = mono_parse_graph_options (argv [i] + 8);
2211 mname = argv [++i];
2212 action = DO_DRAW;
2213 } else if (strcmp (argv [i], "--graph") == 0) {
2214 if (i + 1 >= argc){
2215 fprintf (stderr, "error: --graph option requires a method name argument\n");
2216 return 1;
2219 mname = argv [++i];
2220 mono_graph_options = MONO_GRAPH_CFG;
2221 action = DO_DRAW;
2222 } else if (strcmp (argv [i], "--debug") == 0) {
2223 enable_debugging = TRUE;
2224 } else if (strncmp (argv [i], "--debug=", 8) == 0) {
2225 enable_debugging = TRUE;
2226 if (!parse_debug_options (argv [i] + 8))
2227 return 1;
2228 } else if (strncmp (argv [i], "--debugger-agent=", 17) == 0) {
2229 MonoDebugOptions *opt = mini_get_debug_options ();
2231 sdb_options = g_strdup (argv [i] + 17);
2232 opt->mdb_optimizations = TRUE;
2233 enable_debugging = TRUE;
2234 } else if (strcmp (argv [i], "--security") == 0) {
2235 #ifndef DISABLE_SECURITY
2236 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2237 #else
2238 fprintf (stderr, "error: --security: not compiled with security manager support");
2239 return 1;
2240 #endif
2241 } else if (strncmp (argv [i], "--security=", 11) == 0) {
2242 /* Note: validil, and verifiable need to be
2243 accepted even if DISABLE_SECURITY is defined. */
2245 if (strcmp (argv [i] + 11, "core-clr") == 0) {
2246 #ifndef DISABLE_SECURITY
2247 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2248 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
2249 #else
2250 fprintf (stderr, "error: --security: not compiled with CoreCLR support");
2251 return 1;
2252 #endif
2253 } else if (strcmp (argv [i] + 11, "core-clr-test") == 0) {
2254 #ifndef DISABLE_SECURITY
2255 /* fixme should we enable verifiable code here?*/
2256 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
2257 mono_security_core_clr_test = TRUE;
2258 #else
2259 fprintf (stderr, "error: --security: not compiled with CoreCLR support");
2260 return 1;
2261 #endif
2262 } else if (strcmp (argv [i] + 11, "cas") == 0) {
2263 #ifndef DISABLE_SECURITY
2264 fprintf (stderr, "warning: --security=cas not supported.");
2265 #else
2266 fprintf (stderr, "error: --security: not compiled with CAS support");
2267 return 1;
2268 #endif
2269 } else if (strcmp (argv [i] + 11, "validil") == 0) {
2270 mono_verifier_set_mode (MONO_VERIFIER_MODE_VALID);
2271 } else if (strcmp (argv [i] + 11, "verifiable") == 0) {
2272 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
2273 } else {
2274 fprintf (stderr, "error: --security= option has invalid argument (cas, core-clr, verifiable or validil)\n");
2275 return 1;
2277 } else if (strcmp (argv [i], "--desktop") == 0) {
2278 mono_gc_set_desktop_mode ();
2279 /* Put more desktop-specific optimizations here */
2280 } else if (strcmp (argv [i], "--server") == 0){
2281 mono_config_set_server_mode (TRUE);
2282 /* Put more server-specific optimizations here */
2283 } else if (strcmp (argv [i], "--inside-mdb") == 0) {
2284 action = DO_DEBUGGER;
2285 } else if (strncmp (argv [i], "--wapi=", 7) == 0) {
2286 fprintf (stderr, "--wapi= option no longer supported\n.");
2287 return 1;
2288 } else if (strcmp (argv [i], "--no-x86-stack-align") == 0) {
2289 mono_do_x86_stack_align = FALSE;
2290 #ifdef MONO_JIT_INFO_TABLE_TEST
2291 } else if (strcmp (argv [i], "--test-jit-info-table") == 0) {
2292 test_jit_info_table = TRUE;
2293 #endif
2294 } else if (strcmp (argv [i], "--llvm") == 0) {
2295 #ifndef MONO_ARCH_LLVM_SUPPORTED
2296 fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
2297 #elif !defined(ENABLE_LLVM)
2298 fprintf (stderr, "Mono Warning: --llvm not enabled in this runtime.\n");
2299 #else
2300 mono_use_llvm = TRUE;
2301 #endif
2302 } else if (strcmp (argv [i], "--nollvm") == 0){
2303 mono_use_llvm = FALSE;
2304 } else if ((strcmp (argv [i], "--interpreter") == 0) || !strcmp (argv [i], "--interp")) {
2305 mono_enable_interp (NULL);
2306 } else if (strncmp (argv [i], "--interp=", 9) == 0) {
2307 mono_enable_interp (argv [i] + 9);
2308 } else if (strncmp (argv [i], "--assembly-loader=", strlen("--assembly-loader=")) == 0) {
2309 gchar *arg = argv [i] + strlen ("--assembly-loader=");
2310 if (strcmp (arg, "strict") == 0)
2311 mono_loader_set_strict_strong_names (TRUE);
2312 else if (strcmp (arg, "legacy") == 0)
2313 mono_loader_set_strict_strong_names (FALSE);
2314 else
2315 fprintf (stderr, "Warning: unknown argument to --assembly-loader. Should be \"strict\" or \"legacy\"\n");
2316 } else if (strncmp (argv [i], MONO_HANDLERS_ARGUMENT, MONO_HANDLERS_ARGUMENT_LEN) == 0) {
2317 //Install specific custom handlers.
2318 if (!mono_runtime_install_custom_handlers (argv[i] + MONO_HANDLERS_ARGUMENT_LEN)) {
2319 fprintf (stderr, "error: " MONO_HANDLERS_ARGUMENT ", one or more unknown handlers: '%s'\n", argv [i]);
2320 return 1;
2322 } else if (strcmp (argv [i], "--help-handlers") == 0) {
2323 mono_runtime_install_custom_handlers_usage ();
2324 return 0;
2325 } else if (strncmp (argv [i], "--response=", 11) == 0){
2326 gchar *text;
2327 gsize len;
2329 if (!g_file_get_contents (&argv[i][11], &text, &len, NULL)){
2330 fprintf (stderr, "The specified response file can not be read\n");
2331 exit (1);
2333 mono_parse_options (text, &argc, &argv, FALSE);
2334 g_free (text);
2335 } else if (argv [i][0] == '-' && argv [i][1] == '-' && mini_parse_debug_option (argv [i] + 2)) {
2336 } else {
2337 fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
2338 return 1;
2342 #if defined(DISABLE_HW_TRAPS) || defined(MONO_ARCH_DISABLE_HW_TRAPS)
2343 // Signal handlers not available
2345 MonoDebugOptions *opt = mini_get_debug_options ();
2346 opt->explicit_null_checks = TRUE;
2348 #endif
2350 if (!argv [i]) {
2351 mini_usage ();
2352 return 1;
2356 * XXX: verify if other OSes need it; many platforms seem to have it so that
2357 * mono_w32process_get_path -> mono_w32process_get_name, and the name is not
2358 * necessarily a path instead of just the program name
2360 #if defined (_AIX)
2362 * mono_w32process_get_path on these can only return a name, not a path;
2363 * which may not be good for us if the mono command name isn't on $PATH,
2364 * like in CI scenarios. chances are argv based is fine if we inherited
2365 * the environment variables.
2367 mono_w32process_set_cli_launcher (argv [0]);
2368 #elif !defined(HOST_WIN32) && defined(HAVE_UNISTD_H)
2370 * If we are not embedded, use the mono runtime executable to run managed exe's.
2373 char *runtime_path;
2375 runtime_path = mono_w32process_get_path (getpid ());
2376 if (runtime_path) {
2377 mono_w32process_set_cli_launcher (runtime_path);
2378 g_free (runtime_path);
2381 #endif
2383 if (g_hasenv ("MONO_XDEBUG"))
2384 enable_debugging = TRUE;
2386 #ifdef MONO_CROSS_COMPILE
2387 if (!mono_compile_aot) {
2388 fprintf (stderr, "This mono runtime is compiled for cross-compiling. Only the --aot option is supported.\n");
2389 exit (1);
2391 #if TARGET_SIZEOF_VOID_P == 4 && (defined(TARGET_ARM64) || defined(TARGET_AMD64))
2392 fprintf (stderr, "Can't cross-compile on 32-bit platforms to 64-bit architecture.\n");
2393 exit (1);
2394 #endif
2395 #endif
2397 if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
2398 g_set_prgname (argv[i]);
2401 mono_counters_init ();
2403 #ifndef HOST_WIN32
2404 mono_w32handle_init ();
2405 #endif
2407 /* Set rootdir before loading config */
2408 mono_set_rootdir ();
2410 mono_attach_parse_options (attach_options);
2412 if (trace_options != NULL){
2414 * Need to call this before mini_init () so we can trace methods
2415 * compiled there too.
2417 mono_jit_trace_calls = mono_trace_set_options (trace_options);
2418 if (mono_jit_trace_calls == NULL)
2419 exit (1);
2422 #ifdef DISABLE_JIT
2423 if (!mono_aot_only) {
2424 fprintf (stderr, "This runtime has been configured with --enable-minimal=jit, so the --full-aot command line option is required.\n");
2425 exit (1);
2427 #endif
2429 if (action == DO_DEBUGGER) {
2430 enable_debugging = TRUE;
2431 g_print ("The Mono Debugger is no longer supported.\n");
2432 return 1;
2433 } else if (enable_debugging)
2434 mono_debug_init (MONO_DEBUG_FORMAT_MONO);
2436 #ifdef HOST_WIN32
2437 if (mixed_mode)
2438 mono_load_coree (argv [i]);
2439 #endif
2441 /* Parse gac loading options before loading assemblies. */
2442 if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER || action == DO_REGRESSION) {
2443 mono_config_parse (config_file);
2446 mono_set_defaults (mini_verbose, opt);
2447 domain = mini_init (argv [i], forced_version);
2449 mono_gc_set_stack_end (&domain);
2451 if (agents) {
2452 int i;
2454 for (i = 0; i < agents->len; ++i) {
2455 int res = load_agent (domain, (char*)g_ptr_array_index (agents, i));
2456 if (res) {
2457 g_ptr_array_free (agents, TRUE);
2458 mini_cleanup (domain);
2459 return 1;
2463 g_ptr_array_free (agents, TRUE);
2466 switch (action) {
2467 case DO_SINGLE_METHOD_REGRESSION:
2468 case DO_REGRESSION:
2469 return mono_exec_regression_internal (mini_verbose, argc -i, argv + i, action == DO_SINGLE_METHOD_REGRESSION);
2471 case DO_BENCH:
2472 if (argc - i != 1 || mname == NULL) {
2473 g_print ("Usage: mini --ncompile num --compile method assembly\n");
2474 mini_cleanup (domain);
2475 return 1;
2477 aname = argv [i];
2478 break;
2479 case DO_COMPILE:
2480 if (argc - i != 1) {
2481 mini_usage ();
2482 mini_cleanup (domain);
2483 return 1;
2485 aname = argv [i];
2486 break;
2487 case DO_DRAW:
2488 if (argc - i != 1 || mname == NULL) {
2489 mini_usage ();
2490 mini_cleanup (domain);
2491 return 1;
2493 aname = argv [i];
2494 break;
2495 default:
2496 if (argc - i < 1) {
2497 mini_usage ();
2498 mini_cleanup (domain);
2499 return 1;
2501 aname = argv [i];
2502 break;
2505 #ifdef MONO_JIT_INFO_TABLE_TEST
2506 if (test_jit_info_table)
2507 jit_info_table_test (domain);
2508 #endif
2510 if (mono_compile_aot && extra_bindings_config_file != NULL) {
2511 apply_root_domain_configuration_file_bindings (domain, extra_bindings_config_file);
2514 MonoAssemblyOpenRequest open_req;
2515 mono_assembly_request_prepare (&open_req.request, sizeof (open_req), MONO_ASMCTX_DEFAULT);
2516 assembly = mono_assembly_request_open (aname, &open_req, &open_status);
2517 if (!assembly) {
2518 fprintf (stderr, "Cannot open assembly '%s': %s.\n", aname, mono_image_strerror (open_status));
2519 mini_cleanup (domain);
2520 return 2;
2523 mono_callspec_set_assembly (assembly);
2525 if (mono_compile_aot || action == DO_EXEC) {
2526 const char *error;
2528 //mono_set_rootdir ();
2530 error = mono_check_corlib_version ();
2531 if (error) {
2532 fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
2533 fprintf (stderr, "Loaded from: %s\n",
2534 mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown");
2535 fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.mono-project.com/download.\n");
2536 exit (1);
2539 #if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
2540 /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
2541 if (!enable_debugging && !mono_compile_aot && mono_assembly_get_image_internal (assembly)->image_info->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
2542 FreeConsole ();
2543 #endif
2545 main_args.domain = domain;
2546 main_args.file = aname;
2547 main_args.argc = argc - i;
2548 main_args.argv = argv + i;
2549 main_args.opts = opt;
2550 main_args.aot_options = aot_options;
2551 main_thread_handler (&main_args);
2552 mono_thread_manage ();
2554 mini_cleanup (domain);
2556 /* Look up return value from System.Environment.ExitCode */
2557 i = mono_environment_exitcode_get ();
2558 return i;
2559 } else if (action == DO_COMPILE) {
2560 compile_all_methods (assembly, mini_verbose, opt, recompilation_times);
2561 mini_cleanup (domain);
2562 return 0;
2563 } else if (action == DO_DEBUGGER) {
2564 return 1;
2566 desc = mono_method_desc_new (mname, 0);
2567 if (!desc) {
2568 g_print ("Invalid method name %s\n", mname);
2569 mini_cleanup (domain);
2570 return 3;
2572 method = mono_method_desc_search_in_image (desc, mono_assembly_get_image_internal (assembly));
2573 if (!method) {
2574 g_print ("Cannot find method %s\n", mname);
2575 mini_cleanup (domain);
2576 return 3;
2579 #ifndef DISABLE_JIT
2580 if (action == DO_DRAW) {
2581 int part = 0;
2583 switch (mono_graph_options) {
2584 case MONO_GRAPH_DTREE:
2585 part = 1;
2586 opt |= MONO_OPT_LOOP;
2587 break;
2588 case MONO_GRAPH_CFG_CODE:
2589 part = 1;
2590 break;
2591 case MONO_GRAPH_CFG_SSA:
2592 part = 2;
2593 break;
2594 case MONO_GRAPH_CFG_OPTCODE:
2595 part = 3;
2596 break;
2597 default:
2598 break;
2601 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2602 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
2603 MonoMethod *nm;
2604 nm = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
2605 cfg = mini_method_compile (nm, opt, mono_get_root_domain (), (JitFlags)0, part, -1);
2607 else
2608 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, part, -1);
2609 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
2610 g_warning ("no SSA info available (use -O=deadce)");
2611 return 1;
2613 mono_draw_graph (cfg, mono_graph_options);
2614 mono_destroy_compile (cfg);
2616 } else if (action == DO_BENCH) {
2617 if (mini_stats_fd) {
2618 const char *n;
2619 double no_opt_time = 0.0;
2620 GTimer *timer = g_timer_new ();
2621 fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n",
2622 mono_method_full_name (method, TRUE));
2623 fprintf (mini_stats_fd, "@data = (\n");
2624 fprintf (mini_stats_fd, "[");
2625 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
2626 opt = opt_sets [i];
2627 n = mono_opt_descr (opt);
2628 if (!n [0])
2629 n = "none";
2630 fprintf (mini_stats_fd, "\"%s\",", n);
2632 fprintf (mini_stats_fd, "],\n[");
2634 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
2635 int j;
2636 double elapsed;
2637 opt = opt_sets [i];
2638 g_timer_start (timer);
2639 for (j = 0; j < count; ++j) {
2640 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2641 mono_destroy_compile (cfg);
2643 g_timer_stop (timer);
2644 elapsed = g_timer_elapsed (timer, NULL);
2645 if (!opt)
2646 no_opt_time = elapsed;
2647 fprintf (mini_stats_fd, "%f, ", elapsed);
2649 fprintf (mini_stats_fd, "]");
2650 if (no_opt_time > 0.0) {
2651 fprintf (mini_stats_fd, ", \n[");
2652 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++)
2653 fprintf (mini_stats_fd, "%f,", no_opt_time);
2654 fprintf (mini_stats_fd, "]");
2656 fprintf (mini_stats_fd, ");\n");
2657 } else {
2658 for (i = 0; i < count; ++i) {
2659 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2660 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
2661 method = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
2663 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2664 mono_destroy_compile (cfg);
2667 } else {
2668 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2669 mono_destroy_compile (cfg);
2671 #endif
2673 mini_cleanup (domain);
2674 return 0;
2678 * mono_jit_init:
2680 MonoDomain *
2681 mono_jit_init (const char *file)
2683 return mini_init (file, NULL);
2687 * mono_jit_init_version:
2688 * \param domain_name the name of the root domain
2689 * \param runtime_version the version of the runtime to load
2691 * Use this version when you want to force a particular runtime
2692 * version to be used. By default Mono will pick the runtime that is
2693 * referenced by the initial assembly (specified in \p file), this
2694 * routine allows programmers to specify the actual runtime to be used
2695 * as the initial runtime is inherited by all future assemblies loaded
2696 * (since Mono does not support having more than one mscorlib runtime
2697 * loaded at once).
2699 * The \p runtime_version can be one of these strings: "v4.0.30319" for
2700 * desktop, "mobile" for mobile or "moonlight" for Silverlight compat.
2701 * If an unrecognized string is input, the vm will default to desktop.
2703 * \returns the \c MonoDomain representing the domain where the assembly
2704 * was loaded.
2706 MonoDomain *
2707 mono_jit_init_version (const char *domain_name, const char *runtime_version)
2709 return mini_init (domain_name, runtime_version);
2713 * mono_jit_cleanup:
2715 void
2716 mono_jit_cleanup (MonoDomain *domain)
2718 MONO_ENTER_GC_UNSAFE;
2719 mono_thread_manage ();
2721 mini_cleanup (domain);
2722 MONO_EXIT_GC_UNSAFE;
2725 void
2726 mono_jit_set_aot_only (gboolean val)
2728 mono_aot_only = val;
2731 static void
2732 mono_runtime_set_execution_mode (MonoEEMode mode)
2734 memset (&mono_ee_features, 0, sizeof (mono_ee_features));
2736 switch (mode) {
2737 case MONO_AOT_MODE_LLVMONLY:
2738 mono_aot_only = TRUE;
2739 mono_llvm_only = TRUE;
2741 mono_ee_features.use_aot_trampolines = TRUE;
2742 break;
2744 case MONO_AOT_MODE_FULL:
2745 mono_aot_only = TRUE;
2747 mono_ee_features.use_aot_trampolines = TRUE;
2748 break;
2750 case MONO_AOT_MODE_HYBRID:
2751 mono_set_generic_sharing_vt_supported (TRUE);
2752 mono_set_partial_sharing_supported (TRUE);
2753 break;
2755 case MONO_AOT_MODE_INTERP:
2756 mono_aot_only = TRUE;
2757 mono_use_interpreter = TRUE;
2759 mono_ee_features.use_aot_trampolines = TRUE;
2760 break;
2762 case MONO_AOT_MODE_INTERP_LLVMONLY:
2763 mono_aot_only = TRUE;
2764 mono_use_interpreter = TRUE;
2765 mono_llvm_only = TRUE;
2767 mono_ee_features.force_use_interpreter = TRUE;
2768 break;
2770 case MONO_EE_MODE_INTERP:
2771 mono_use_interpreter = TRUE;
2773 mono_ee_features.force_use_interpreter = TRUE;
2774 break;
2776 case MONO_AOT_MODE_NORMAL:
2777 case MONO_AOT_MODE_NONE:
2778 break;
2780 default:
2781 g_error ("Unknown execution-mode %d", mode);
2786 * mono_jit_set_aot_mode:
2788 void
2789 mono_jit_set_aot_mode (MonoAotMode mode)
2791 /* we don't want to set mono_aot_mode twice */
2792 static gboolean inited;
2794 g_assert (!inited);
2795 mono_aot_mode = mode;
2796 inited = TRUE;
2798 mono_runtime_set_execution_mode ((MonoEEMode)mode);
2801 mono_bool
2802 mono_jit_aot_compiling (void)
2804 return mono_compile_aot;
2808 * mono_jit_set_trace_options:
2809 * \param options string representing the trace options
2810 * Set the options of the tracing engine. This function can be called before initializing
2811 * the mono runtime. See the --trace mono(1) manpage for the options format.
2813 * \returns TRUE if the options were parsed and set correctly, FALSE otherwise.
2815 gboolean
2816 mono_jit_set_trace_options (const char* options)
2818 MonoCallSpec *trace_opt = mono_trace_set_options (options);
2819 if (trace_opt == NULL)
2820 return FALSE;
2821 mono_jit_trace_calls = trace_opt;
2822 return TRUE;
2826 * mono_set_signal_chaining:
2828 * Enable/disable signal chaining. This should be called before \c mono_jit_init.
2829 * If signal chaining is enabled, the runtime saves the original signal handlers before
2830 * installing its own handlers, and calls the original ones in the following cases:
2831 * - a \c SIGSEGV / \c SIGABRT signal received while executing native (i.e. not JITted) code.
2832 * - \c SIGPROF
2833 * - \c SIGFPE
2834 * - \c SIGQUIT
2835 * - \c SIGUSR2
2836 * Signal chaining only works on POSIX platforms.
2838 void
2839 mono_set_signal_chaining (gboolean chain_signals)
2841 mono_do_signal_chaining = chain_signals;
2845 * mono_set_crash_chaining:
2847 * Enable/disable crash chaining due to signals. When a fatal signal is delivered and
2848 * Mono doesn't know how to handle it, it will invoke the crash handler. If chrash chaining
2849 * is enabled, it will first print its crash information and then try to chain with the native handler.
2851 void
2852 mono_set_crash_chaining (gboolean chain_crashes)
2854 mono_do_crash_chaining = chain_crashes;
2858 * mono_parse_options_from:
2859 * \param options string containing strings
2860 * \param ref_argc pointer to the \c argc variable that might be updated
2861 * \param ref_argv pointer to the \c argv string vector variable that might be updated
2863 * This function parses the contents of the \c MONO_ENV_OPTIONS
2864 * environment variable as if they were parsed by a command shell
2865 * splitting the contents by spaces into different elements of the
2866 * \p argv vector. This method supports quoting with both the " and '
2867 * characters. Inside quoting, spaces and tabs are significant,
2868 * otherwise, they are considered argument separators.
2870 * The \ character can be used to escape the next character which will
2871 * be added to the current element verbatim. Typically this is used
2872 * inside quotes. If the quotes are not balanced, this method
2874 * If the environment variable is empty, no changes are made
2875 * to the values pointed by \p ref_argc and \p ref_argv.
2877 * Otherwise the \p ref_argv is modified to point to a new array that contains
2878 * all the previous elements contained in the vector, plus the values parsed.
2879 * The \p argc is updated to match the new number of parameters.
2881 * \returns The value NULL is returned on success, otherwise a \c g_strdup allocated
2882 * string is returned (this is an alias to \c malloc under normal circumstances) that
2883 * contains the error message that happened during parsing.
2885 char *
2886 mono_parse_options_from (const char *options, int *ref_argc, char **ref_argv [])
2888 return mono_parse_options (options, ref_argc, ref_argv, TRUE);
2891 static char *
2892 mono_parse_options (const char *options, int *ref_argc, char **ref_argv [], gboolean prepend)
2894 int argc = *ref_argc;
2895 char **argv = *ref_argv;
2896 GPtrArray *array = g_ptr_array_new ();
2897 GString *buffer = g_string_new ("");
2898 const char *p;
2899 unsigned i;
2900 gboolean in_quotes = FALSE;
2901 char quote_char = '\0';
2903 if (options == NULL)
2904 return NULL;
2906 for (p = options; *p; p++){
2907 switch (*p){
2908 case ' ': case '\t': case '\n':
2909 if (!in_quotes) {
2910 if (buffer->len != 0){
2911 g_ptr_array_add (array, g_strdup (buffer->str));
2912 g_string_truncate (buffer, 0);
2914 } else {
2915 g_string_append_c (buffer, *p);
2917 break;
2918 case '\\':
2919 if (p [1]){
2920 g_string_append_c (buffer, p [1]);
2921 p++;
2923 break;
2924 case '\'':
2925 case '"':
2926 if (in_quotes) {
2927 if (quote_char == *p)
2928 in_quotes = FALSE;
2929 else
2930 g_string_append_c (buffer, *p);
2931 } else {
2932 in_quotes = TRUE;
2933 quote_char = *p;
2935 break;
2936 default:
2937 g_string_append_c (buffer, *p);
2938 break;
2941 if (in_quotes)
2942 return g_strdup_printf ("Unmatched quotes in value: [%s]\n", options);
2944 if (buffer->len != 0)
2945 g_ptr_array_add (array, g_strdup (buffer->str));
2946 g_string_free (buffer, TRUE);
2948 if (array->len > 0){
2949 int new_argc = array->len + argc;
2950 char **new_argv = g_new (char *, new_argc + 1);
2951 int j;
2953 new_argv [0] = argv [0];
2955 i = 1;
2956 if (prepend){
2957 /* First the environment variable settings, to allow the command line options to override */
2958 for (i = 0; i < array->len; i++)
2959 new_argv [i+1] = (char *)g_ptr_array_index (array, i);
2960 i++;
2962 for (j = 1; j < argc; j++)
2963 new_argv [i++] = argv [j];
2964 if (!prepend){
2965 for (j = 0; j < array->len; j++)
2966 new_argv [i++] = (char *)g_ptr_array_index (array, j);
2968 new_argv [i] = NULL;
2970 *ref_argc = new_argc;
2971 *ref_argv = new_argv;
2973 g_ptr_array_free (array, TRUE);
2974 return NULL;
2978 * mono_parse_env_options:
2979 * \param ref_argc pointer to the \c argc variable that might be updated
2980 * \param ref_argv pointer to the \c argv string vector variable that might be updated
2982 * This function parses the contents of the \c MONO_ENV_OPTIONS
2983 * environment variable as if they were parsed by a command shell
2984 * splitting the contents by spaces into different elements of the
2985 * \p argv vector. This method supports quoting with both the " and '
2986 * characters. Inside quoting, spaces and tabs are significant,
2987 * otherwise, they are considered argument separators.
2989 * The \ character can be used to escape the next character which will
2990 * be added to the current element verbatim. Typically this is used
2991 * inside quotes. If the quotes are not balanced, this method
2993 * If the environment variable is empty, no changes are made
2994 * to the values pointed by \p ref_argc and \p ref_argv.
2996 * Otherwise the \p ref_argv is modified to point to a new array that contains
2997 * all the previous elements contained in the vector, plus the values parsed.
2998 * The \p argc is updated to match the new number of parameters.
3000 * If there is an error parsing, this method will terminate the process by
3001 * calling exit(1).
3003 * An alternative to this method that allows an arbitrary string to be parsed
3004 * and does not exit on error is the `api:mono_parse_options_from`.
3006 void
3007 mono_parse_env_options (int *ref_argc, char **ref_argv [])
3009 char *ret;
3011 char *env_options = g_getenv ("MONO_ENV_OPTIONS");
3012 if (env_options == NULL)
3013 return;
3014 ret = mono_parse_options_from (env_options, ref_argc, ref_argv);
3015 g_free (env_options);
3016 if (ret == NULL)
3017 return;
3018 fprintf (stderr, "%s", ret);
3019 exit (1);