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