Merge branch 'alexischr/nursery-canaries-managed-alloc'
[mono.git] / mono / mini / driver.c
1 /*
2  * driver.c: The new mono JIT compiler.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002-2003 Ximian, Inc.
9  * (C) 2003-2006 Novell, Inc.
10  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
11  */
12
13 #include <config.h>
14 #ifdef HAVE_SIGNAL_H
15 #include <signal.h>
16 #endif
17 #if HAVE_SCHED_SETAFFINITY
18 #include <sched.h>
19 #endif
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23
24 #include <mono/metadata/assembly.h>
25 #include <mono/metadata/loader.h>
26 #include <mono/metadata/tabledefs.h>
27 #include <mono/metadata/class.h>
28 #include <mono/metadata/object.h>
29 #include <mono/metadata/exception.h>
30 #include <mono/metadata/opcodes.h>
31 #include <mono/metadata/mono-endian.h>
32 #include <mono/metadata/tokentype.h>
33 #include <mono/metadata/tabledefs.h>
34 #include <mono/metadata/threads.h>
35 #include <mono/metadata/marshal.h>
36 #include <mono/metadata/socket-io.h>
37 #include <mono/metadata/appdomain.h>
38 #include <mono/metadata/debug-helpers.h>
39 #include <mono/io-layer/io-layer.h>
40 #include "mono/metadata/profiler.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
58 #include "mini.h"
59 #include "jit.h"
60 #include "aot-compiler.h"
61
62 #include <string.h>
63 #include <ctype.h>
64 #include <locale.h>
65 #include "version.h"
66 #include "debugger-agent.h"
67 #if TARGET_OSX
68 #   include <sys/resource.h>
69 #endif
70
71 static FILE *mini_stats_fd;
72
73 static void mini_usage (void);
74
75 #ifdef HOST_WIN32
76 /* Need this to determine whether to detach console */
77 #include <mono/metadata/cil-coff.h>
78 /* This turns off command line globbing under win32 */
79 int _CRT_glob = 0;
80 #endif
81
82 typedef void (*OptFunc) (const char *p);
83
84 #undef OPTFLAG
85 #ifdef HAVE_ARRAY_ELEM_INIT
86 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
87 #define MSGSTRFIELD1(line) str##line
88
89 static const struct msgstr_t {
90 #define OPTFLAG(id,shift,name,desc) char MSGSTRFIELD(__LINE__) [sizeof (name) + sizeof (desc)];
91 #include "optflags-def.h"
92 #undef OPTFLAG
93 } opstr = {
94 #define OPTFLAG(id,shift,name,desc) name "\0" desc,
95 #include "optflags-def.h"
96 #undef OPTFLAG
97 };
98 static const gint16 opt_names [] = {
99 #define OPTFLAG(id,shift,name,desc) [(shift)] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
100 #include "optflags-def.h"
101 #undef OPTFLAG
102 };
103
104 #define optflag_get_name(id) ((const char*)&opstr + opt_names [(id)])
105 #define optflag_get_desc(id) (optflag_get_name(id) + 1 + strlen (optflag_get_name(id)))
106
107 #else /* !HAVE_ARRAY_ELEM_INIT */
108 typedef struct {
109         const char* name;
110         const char* desc;
111 } OptName;
112
113 #define OPTFLAG(id,shift,name,desc) {name,desc},
114 static const OptName 
115 opt_names [] = {
116 #include "optflags-def.h"
117         {NULL, NULL}
118 };
119 #define optflag_get_name(id) (opt_names [(id)].name)
120 #define optflag_get_desc(id) (opt_names [(id)].desc)
121
122 #endif
123
124 static const OptFunc
125 opt_funcs [sizeof (int) * 8] = {
126         NULL
127 };
128
129 #ifdef __native_client__
130 extern char *nacl_mono_path;
131 #endif
132
133 #define DEFAULT_OPTIMIZATIONS ( \
134         MONO_OPT_PEEPHOLE |     \
135         MONO_OPT_CFOLD |        \
136         MONO_OPT_INLINE |       \
137         MONO_OPT_CONSPROP |     \
138         MONO_OPT_COPYPROP |     \
139         MONO_OPT_DEADCE |       \
140         MONO_OPT_BRANCH |       \
141         MONO_OPT_LINEARS |      \
142         MONO_OPT_INTRINS |  \
143         MONO_OPT_LOOP |  \
144         MONO_OPT_EXCEPTION |  \
145     MONO_OPT_CMOV |  \
146         MONO_OPT_GSHARED |      \
147         MONO_OPT_SIMD | \
148         MONO_OPT_ALIAS_ANALYSIS | \
149         MONO_OPT_AOT)
150
151 #define EXCLUDED_FROM_ALL (MONO_OPT_SHARED | MONO_OPT_PRECOMP | MONO_OPT_UNSAFE | MONO_OPT_GSHAREDVT | MONO_OPT_FLOAT32)
152
153 static guint32
154 parse_optimizations (guint32 opt, const char* p, gboolean cpu_opts)
155 {
156         guint32 exclude = 0;
157         const char *n;
158         int i, invert, len;
159
160         /* Initialize the hwcap module if necessary. */
161         mono_hwcap_init ();
162
163         /* call out to cpu detection code here that sets the defaults ... */
164         if (cpu_opts) {
165                 opt |= mono_arch_cpu_optimizations (&exclude);
166                 opt &= ~exclude;
167         }
168         if (!p)
169                 return opt;
170
171         while (*p) {
172                 if (*p == '-') {
173                         p++;
174                         invert = TRUE;
175                 } else {
176                         invert = FALSE;
177                 }
178                 for (i = 0; i < G_N_ELEMENTS (opt_names) && optflag_get_name (i); ++i) {
179                         n = optflag_get_name (i);
180                         len = strlen (n);
181                         if (strncmp (p, n, len) == 0) {
182                                 if (invert)
183                                         opt &= ~ (1 << i);
184                                 else
185                                         opt |= 1 << i;
186                                 p += len;
187                                 if (*p == ',') {
188                                         p++;
189                                         break;
190                                 } else if (*p == '=') {
191                                         p++;
192                                         if (opt_funcs [i])
193                                                 opt_funcs [i] (p);
194                                         while (*p && *p++ != ',');
195                                         break;
196                                 }
197                                 /* error out */
198                                 break;
199                         }
200                 }
201                 if (i == G_N_ELEMENTS (opt_names) || !optflag_get_name (i)) {
202                         if (strncmp (p, "all", 3) == 0) {
203                                 if (invert)
204                                         opt = 0;
205                                 else
206                                         opt = ~(EXCLUDED_FROM_ALL | exclude);
207                                 p += 3;
208                                 if (*p == ',')
209                                         p++;
210                         } else {
211                                 fprintf (stderr, "Invalid optimization name `%s'\n", p);
212                                 exit (1);
213                         }
214                 }
215         }
216         return opt;
217 }
218
219 static gboolean
220 parse_debug_options (const char* p)
221 {
222         MonoDebugOptions *opt = mini_get_debug_options ();
223
224         do {
225                 if (!*p) {
226                         fprintf (stderr, "Syntax error; expected debug option name\n");
227                         return FALSE;
228                 }
229
230                 if (!strncmp (p, "casts", 5)) {
231                         opt->better_cast_details = TRUE;
232                         p += 5;
233                 } else if (!strncmp (p, "mdb-optimizations", 17)) {
234                         opt->mdb_optimizations = TRUE;
235                         p += 17;
236                 } else if (!strncmp (p, "gdb", 3)) {
237                         opt->gdb = TRUE;
238                         p += 3;
239                 } else {
240                         fprintf (stderr, "Invalid debug option `%s', use --help-debug for details\n", p);
241                         return FALSE;
242                 }
243
244                 if (*p == ',') {
245                         p++;
246                         if (!*p) {
247                                 fprintf (stderr, "Syntax error; expected debug option name\n");
248                                 return FALSE;
249                         }
250                 }
251         } while (*p);
252
253         return TRUE;
254 }
255
256 typedef struct {
257         const char name [6];
258         const char desc [18];
259         MonoGraphOptions value;
260 } GraphName;
261
262 static const GraphName 
263 graph_names [] = {
264         {"cfg",      "Control Flow",                            MONO_GRAPH_CFG},
265         {"dtree",    "Dominator Tree",                          MONO_GRAPH_DTREE},
266         {"code",     "CFG showing code",                        MONO_GRAPH_CFG_CODE},
267         {"ssa",      "CFG after SSA",                           MONO_GRAPH_CFG_SSA},
268         {"optc",     "CFG after IR opts",                       MONO_GRAPH_CFG_OPTCODE}
269 };
270
271 static MonoGraphOptions
272 mono_parse_graph_options (const char* p)
273 {
274         const char *n;
275         int i, len;
276
277         for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
278                 n = graph_names [i].name;
279                 len = strlen (n);
280                 if (strncmp (p, n, len) == 0)
281                         return graph_names [i].value;
282         }
283
284         fprintf (stderr, "Invalid graph name provided: %s\n", p);
285         exit (1);
286 }
287
288 int
289 mono_parse_default_optimizations (const char* p)
290 {
291         guint32 opt;
292
293         opt = parse_optimizations (DEFAULT_OPTIMIZATIONS, p, TRUE);
294         return opt;
295 }
296
297 char*
298 mono_opt_descr (guint32 flags) {
299         GString *str = g_string_new ("");
300         int i, need_comma;
301
302         need_comma = 0;
303         for (i = 0; i < G_N_ELEMENTS (opt_names); ++i) {
304                 if (flags & (1 << i) && optflag_get_name (i)) {
305                         if (need_comma)
306                                 g_string_append_c (str, ',');
307                         g_string_append (str, optflag_get_name (i));
308                         need_comma = 1;
309                 }
310         }
311         return g_string_free (str, FALSE);
312 }
313
314 static const guint32
315 opt_sets [] = {
316        0,
317        MONO_OPT_PEEPHOLE,
318        MONO_OPT_BRANCH,
319        MONO_OPT_CFOLD,
320        MONO_OPT_FCMOV,
321        MONO_OPT_ALIAS_ANALYSIS,
322 #ifdef MONO_ARCH_SIMD_INTRINSICS
323        MONO_OPT_SIMD,
324        MONO_OPT_SSE2,
325        MONO_OPT_SIMD | MONO_OPT_SSE2,
326 #endif
327        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS,
328        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_INTRINS | MONO_OPT_ALIAS_ANALYSIS,
329        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS,
330        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP,
331        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_CFOLD,
332        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE,
333        MONO_OPT_BRANCH | MONO_OPT_PEEPHOLE | MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP | MONO_OPT_DEADCE | MONO_OPT_ALIAS_ANALYSIS,
334        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,
335        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_TAILC,
336        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,
337        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,
338        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,
339        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,
340        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,
341        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,
342        DEFAULT_OPTIMIZATIONS, 
343 };
344
345 typedef int (*TestMethod) (void);
346
347 #if 0
348 static void
349 domain_dump_native_code (MonoDomain *domain) {
350         // need to poke into the domain, move to metadata/domain.c
351         // need to empty jit_info_table and code_mp
352 }
353 #endif
354
355 static void
356 mini_regression_step (MonoImage *image, int verbose, int *total_run, int *total,
357                 guint32 opt_flags,
358                 GTimer *timer, MonoDomain *domain)
359 {
360         int result, expected, failed, cfailed, run, code_size;
361         TestMethod func;
362         double elapsed, comp_time, start_time;
363         char *n;
364         int i;
365
366         mono_set_defaults (verbose, opt_flags);
367         n = mono_opt_descr (opt_flags);
368         g_print ("Test run: image=%s, opts=%s\n", mono_image_get_filename (image), n);
369         g_free (n);
370         cfailed = failed = run = code_size = 0;
371         comp_time = elapsed = 0.0;
372
373         /* fixme: ugly hack - delete all previously compiled methods */
374         if (domain_jit_info (domain)) {
375                 g_hash_table_destroy (domain_jit_info (domain)->jit_trampoline_hash);
376                 domain_jit_info (domain)->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
377                 mono_internal_hash_table_destroy (&(domain->jit_code_hash));
378                 mono_jit_code_hash_init (&(domain->jit_code_hash));
379         }
380
381         g_timer_start (timer);
382         if (mini_stats_fd)
383                 fprintf (mini_stats_fd, "[");
384         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
385                 MonoError error;
386                 MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, &error);
387                 if (!method) {
388                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
389                         continue;
390                 }
391                 if (strncmp (method->name, "test_", 5) == 0) {
392                         MonoCompile *cfg;
393
394                         expected = atoi (method->name + 5);
395                         run++;
396                         start_time = g_timer_elapsed (timer, NULL);
397                         comp_time -= start_time;
398                         cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, opt_flags), mono_get_root_domain (), JIT_FLAG_RUN_CCTORS, 0, -1);
399                         comp_time += g_timer_elapsed (timer, NULL);
400                         if (cfg->exception_type == MONO_EXCEPTION_NONE) {
401                                 if (verbose >= 2)
402                                         g_print ("Running '%s' ...\n", method->name);
403 #ifdef MONO_USE_AOT_COMPILER
404                                 MonoError error;
405                                 func = (TestMethod)mono_aot_get_method_checked (mono_get_root_domain (), method, &error);
406                                 mono_error_cleanup (&error);
407                                 if (!func)
408                                         func = (TestMethod)(gpointer)cfg->native_code;
409 #else
410                                         func = (TestMethod)(gpointer)cfg->native_code;
411 #endif
412                                 func = (TestMethod)mono_create_ftnptr (mono_get_root_domain (), func);
413                                 result = func ();
414                                 if (result != expected) {
415                                         failed++;
416                                         g_print ("Test '%s' failed result (got %d, expected %d).\n", method->name, result, expected);
417                                 }
418                                 code_size += cfg->code_len;
419                                 mono_destroy_compile (cfg);
420
421                         } else {
422                                 cfailed++;
423                                 g_print ("Test '%s' failed compilation.\n", method->name);
424                         }
425                         if (mini_stats_fd)
426                                 fprintf (mini_stats_fd, "%f, ",
427                                                 g_timer_elapsed (timer, NULL) - start_time);
428                 }
429         }
430         if (mini_stats_fd)
431                 fprintf (mini_stats_fd, "],\n");
432         g_timer_stop (timer);
433         elapsed = g_timer_elapsed (timer, NULL);
434         if (failed > 0 || cfailed > 0){
435                 g_print ("Results: total tests: %d, failed: %d, cfailed: %d (pass: %.2f%%)\n",
436                                 run, failed, cfailed, 100.0*(run-failed-cfailed)/run);
437         } else {
438                 g_print ("Results: total tests: %d, all pass \n",  run);
439         }
440
441         g_print ("Elapsed time: %f secs (%f, %f), Code size: %d\n\n", elapsed,
442                         elapsed - comp_time, comp_time, code_size);
443         *total += failed + cfailed;
444         *total_run += run;
445 }
446
447 static int
448 mini_regression (MonoImage *image, int verbose, int *total_run)
449 {
450         guint32 i, opt;
451         MonoMethod *method;
452         char *n;
453         GTimer *timer = g_timer_new ();
454         MonoDomain *domain = mono_domain_get ();
455         guint32 exclude = 0;
456         int total;
457
458         /* Note: mono_hwcap_init () called in mono_init () before we get here. */
459         mono_arch_cpu_optimizations (&exclude);
460
461         if (mini_stats_fd) {
462                 fprintf (mini_stats_fd, "$stattitle = \'Mono Benchmark Results (various optimizations)\';\n");
463
464                 fprintf (mini_stats_fd, "$graph->set_legend(qw(");
465                 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); opt++) {
466                         guint32 opt_flags = opt_sets [opt];
467                         n = mono_opt_descr (opt_flags);
468                         if (!n [0])
469                                 n = (char *)"none";
470                         if (opt)
471                                 fprintf (mini_stats_fd, " ");
472                         fprintf (mini_stats_fd, "%s", n);
473                 
474
475                 }
476                 fprintf (mini_stats_fd, "));\n");
477
478                 fprintf (mini_stats_fd, "@data = (\n");
479                 fprintf (mini_stats_fd, "[");
480         }
481
482         /* load the metadata */
483         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
484                 MonoError error;
485                 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, &error);
486                 if (!method) {
487                         mono_error_cleanup (&error);
488                         continue;
489                 }
490                 mono_class_init (method->klass);
491
492                 if (!strncmp (method->name, "test_", 5) && mini_stats_fd) {
493                         fprintf (mini_stats_fd, "\"%s\",", method->name);
494                 }
495         }
496         if (mini_stats_fd)
497                 fprintf (mini_stats_fd, "],\n");
498
499
500         total = 0;
501         *total_run = 0;
502         if (mono_do_single_method_regression) {
503                 GSList *iter;
504
505                 mini_regression_step (image, verbose, total_run, &total,
506                                 0,
507                                 timer, domain);
508                 if (total)
509                         return total;
510                 g_print ("Single method regression: %d methods\n", g_slist_length (mono_single_method_list));
511
512                 for (iter = mono_single_method_list; iter; iter = g_slist_next (iter)) {
513                         char *method_name;
514
515                         mono_current_single_method = (MonoMethod *)iter->data;
516
517                         method_name = mono_method_full_name (mono_current_single_method, TRUE);
518                         g_print ("Current single method: %s\n", method_name);
519                         g_free (method_name);
520
521                         mini_regression_step (image, verbose, total_run, &total,
522                                         0,
523                                         timer, domain);
524                         if (total)
525                                 return total;
526                 }
527         } else {
528                 for (opt = 0; opt < G_N_ELEMENTS (opt_sets); ++opt) {
529                         mini_regression_step (image, verbose, total_run, &total,
530                                         opt_sets [opt] & ~exclude,
531                                         timer, domain);
532                 }
533         }
534
535         if (mini_stats_fd) {
536                 fprintf (mini_stats_fd, ");\n");
537                 fflush (mini_stats_fd);
538         }
539
540         g_timer_destroy (timer);
541         return total;
542 }
543
544 static int
545 mini_regression_list (int verbose, int count, char *images [])
546 {
547         int i, total, total_run, run;
548         MonoAssembly *ass;
549         
550         total_run =  total = 0;
551         for (i = 0; i < count; ++i) {
552                 ass = mono_assembly_open (images [i], NULL);
553                 if (!ass) {
554                         g_warning ("failed to load assembly: %s", images [i]);
555                         continue;
556                 }
557                 total += mini_regression (mono_assembly_get_image (ass), verbose, &run);
558                 total_run += run;
559         }
560         if (total > 0){
561                 g_print ("Overall results: tests: %d, failed: %d, opt combinations: %d (pass: %.2f%%)\n", 
562                          total_run, total, (int)G_N_ELEMENTS (opt_sets), 100.0*(total_run-total)/total_run);
563         } else {
564                 g_print ("Overall results: tests: %d, 100%% pass, opt combinations: %d\n", 
565                          total_run, (int)G_N_ELEMENTS (opt_sets));
566         }
567         
568         return total;
569 }
570
571 #ifdef MONO_JIT_INFO_TABLE_TEST
572 typedef struct _JitInfoData
573 {
574         guint start;
575         guint length;
576         MonoJitInfo *ji;
577         struct _JitInfoData *next;
578 } JitInfoData;
579
580 typedef struct
581 {
582         guint start;
583         guint length;
584         int num_datas;
585         JitInfoData *data;
586 } Region;
587
588 typedef struct
589 {
590         int num_datas;
591         int num_regions;
592         Region *regions;
593         int num_frees;
594         JitInfoData *frees;
595 } ThreadData;
596
597 static int num_threads;
598 static ThreadData *thread_datas;
599 static MonoDomain *test_domain;
600
601 static JitInfoData*
602 alloc_random_data (Region *region)
603 {
604         JitInfoData **data;
605         JitInfoData *prev;
606         guint prev_end;
607         guint next_start;
608         guint max_len;
609         JitInfoData *d;
610         int num_retries = 0;
611         int pos, i;
612
613  restart:
614         prev = NULL;
615         data = &region->data;
616         pos = random () % (region->num_datas + 1);
617         i = 0;
618         while (*data != NULL) {
619                 if (i++ == pos)
620                         break;
621                 prev = *data;
622                 data = &(*data)->next;
623         }
624
625         if (prev == NULL)
626                 g_assert (*data == region->data);
627         else
628                 g_assert (prev->next == *data);
629
630         if (prev == NULL)
631                 prev_end = region->start;
632         else
633                 prev_end = prev->start + prev->length;
634
635         if (*data == NULL)
636                 next_start = region->start + region->length;
637         else
638                 next_start = (*data)->start;
639
640         g_assert (prev_end <= next_start);
641
642         max_len = next_start - prev_end;
643         if (max_len < 128) {
644                 if (++num_retries >= 10)
645                         return NULL;
646                 goto restart;
647         }
648         if (max_len > 1024)
649                 max_len = 1024;
650
651         d = g_new0 (JitInfoData, 1);
652         d->start = prev_end + random () % (max_len / 2);
653         d->length = random () % MIN (max_len, next_start - d->start) + 1;
654
655         g_assert (d->start >= prev_end && d->start + d->length <= next_start);
656
657         d->ji = g_new0 (MonoJitInfo, 1);
658         d->ji->d.method = (MonoMethod*) 0xABadBabe;
659         d->ji->code_start = (gpointer)(gulong) d->start;
660         d->ji->code_size = d->length;
661         d->ji->cas_inited = 1;  /* marks an allocated jit info */
662
663         d->next = *data;
664         *data = d;
665
666         ++region->num_datas;
667
668         return d;
669 }
670
671 static JitInfoData**
672 choose_random_data (Region *region)
673 {
674         int n;
675         int i;
676         JitInfoData **d;
677
678         g_assert (region->num_datas > 0);
679
680         n = random () % region->num_datas;
681
682         for (d = &region->data, i = 0;
683              i < n;
684              d = &(*d)->next, ++i)
685                 ;
686
687         return d;
688 }
689
690 static Region*
691 choose_random_region (ThreadData *td)
692 {
693         return &td->regions [random () % td->num_regions];
694 }
695
696 static ThreadData*
697 choose_random_thread (void)
698 {
699         return &thread_datas [random () % num_threads];
700 }
701
702 static void
703 free_jit_info_data (ThreadData *td, JitInfoData *free)
704 {
705         free->next = td->frees;
706         td->frees = free;
707
708         if (++td->num_frees >= 1000) {
709                 int i;
710
711                 for (i = 0; i < 500; ++i)
712                         free = free->next;
713
714                 while (free->next != NULL) {
715                         JitInfoData *next = free->next->next;
716
717                         //g_free (free->next->ji);
718                         g_free (free->next);
719                         free->next = next;
720
721                         --td->num_frees;
722                 }
723         }
724 }
725
726 #define NUM_THREADS             8
727 #define REGIONS_PER_THREAD      10
728 #define REGION_SIZE             0x10000
729
730 #define MAX_ADDR                (REGION_SIZE * REGIONS_PER_THREAD * NUM_THREADS)
731
732 #define MODE_ALLOC      1
733 #define MODE_FREE       2
734
735 static void
736 test_thread_func (ThreadData *td)
737 {
738         int mode = MODE_ALLOC;
739         int i = 0;
740         gulong lookup_successes = 0, lookup_failures = 0;
741         MonoDomain *domain = test_domain;
742         int thread_num = (int)(td - thread_datas);
743         gboolean modify_thread = thread_num < NUM_THREADS / 2; /* only half of the threads modify the table */
744
745         for (;;) {
746                 int alloc;
747                 int lookup = 1;
748
749                 if (td->num_datas == 0) {
750                         lookup = 0;
751                         alloc = 1;
752                 } else if (modify_thread && random () % 1000 < 5) {
753                         lookup = 0;
754                         if (mode == MODE_ALLOC)
755                                 alloc = (random () % 100) < 70;
756                         else if (mode == MODE_FREE)
757                                 alloc = (random () % 100) < 30;
758                 }
759
760                 if (lookup) {
761                         /* modify threads sometimes look up their own jit infos */
762                         if (modify_thread && random () % 10 < 5) {
763                                 Region *region = choose_random_region (td);
764
765                                 if (region->num_datas > 0) {
766                                         JitInfoData **data = choose_random_data (region);
767                                         guint pos = (*data)->start + random () % (*data)->length;
768                                         MonoJitInfo *ji;
769
770                                         ji = mono_jit_info_table_find (domain, (char*)(gulong) pos);
771
772                                         g_assert (ji->cas_inited);
773                                         g_assert ((*data)->ji == ji);
774                                 }
775                         } else {
776                                 int pos = random () % MAX_ADDR;
777                                 char *addr = (char*)(gulong) pos;
778                                 MonoJitInfo *ji;
779
780                                 ji = mono_jit_info_table_find (domain, addr);
781
782                                 /*
783                                  * FIXME: We are actually not allowed
784                                  * to do this.  By the time we examine
785                                  * the ji another thread might already
786                                  * have removed it.
787                                  */
788                                 if (ji != NULL) {
789                                         g_assert (addr >= (char*)ji->code_start && addr < (char*)ji->code_start + ji->code_size);
790                                         ++lookup_successes;
791                                 } else
792                                         ++lookup_failures;
793                         }
794                 } else if (alloc) {
795                         JitInfoData *data = alloc_random_data (choose_random_region (td));
796
797                         if (data != NULL) {
798                                 mono_jit_info_table_add (domain, data->ji);
799
800                                 ++td->num_datas;
801                         }
802                 } else {
803                         Region *region = choose_random_region (td);
804
805                         if (region->num_datas > 0) {
806                                 JitInfoData **data = choose_random_data (region);
807                                 JitInfoData *free;
808
809                                 mono_jit_info_table_remove (domain, (*data)->ji);
810
811                                 //(*data)->ji->cas_inited = 0; /* marks a free jit info */
812
813                                 free = *data;
814                                 *data = (*data)->next;
815
816                                 free_jit_info_data (td, free);
817
818                                 --region->num_datas;
819                                 --td->num_datas;
820                         }
821                 }
822
823                 if (++i % 100000 == 0) {
824                         int j;
825                         g_print ("num datas %d (%ld - %ld): %d", (int)(td - thread_datas),
826                                  lookup_successes, lookup_failures, td->num_datas);
827                         for (j = 0; j < td->num_regions; ++j)
828                                 g_print ("  %d", td->regions [j].num_datas);
829                         g_print ("\n");
830                 }
831
832                 if (td->num_datas < 100)
833                         mode = MODE_ALLOC;
834                 else if (td->num_datas > 2000)
835                         mode = MODE_FREE;
836         }
837 }
838
839 /*
840 static void
841 small_id_thread_func (gpointer arg)
842 {
843         MonoThread *thread = mono_thread_current ();
844         MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
845
846         g_print ("my small id is %d\n", (int)thread->small_id);
847         mono_hazard_pointer_clear (hp, 1);
848         sleep (3);
849         g_print ("done %d\n", (int)thread->small_id);
850 }
851 */
852
853 static void
854 jit_info_table_test (MonoDomain *domain)
855 {
856         MonoError error;
857         int i;
858
859         g_print ("testing jit_info_table\n");
860
861         num_threads = NUM_THREADS;
862         thread_datas = g_new0 (ThreadData, num_threads);
863
864         for (i = 0; i < num_threads; ++i) {
865                 int j;
866
867                 thread_datas [i].num_regions = REGIONS_PER_THREAD;
868                 thread_datas [i].regions = g_new0 (Region, REGIONS_PER_THREAD);
869
870                 for (j = 0; j < REGIONS_PER_THREAD; ++j) {
871                         thread_datas [i].regions [j].start = (num_threads * j + i) * REGION_SIZE;
872                         thread_datas [i].regions [j].length = REGION_SIZE;
873                 }
874         }
875
876         test_domain = domain;
877
878         /*
879         for (i = 0; i < 72; ++i)
880                 mono_thread_create (domain, small_id_thread_func, NULL);
881
882         sleep (2);
883         */
884
885         for (i = 0; i < num_threads; ++i) {
886                 mono_thread_create_checked (domain, test_thread_func, &thread_datas [i], &error);
887                 mono_error_assert_ok (&error);
888         }
889 }
890 #endif
891
892 enum {
893         DO_BENCH,
894         DO_REGRESSION,
895         DO_SINGLE_METHOD_REGRESSION,
896         DO_COMPILE,
897         DO_EXEC,
898         DO_DRAW,
899         DO_DEBUGGER
900 };
901
902 typedef struct CompileAllThreadArgs {
903         MonoAssembly *ass;
904         int verbose;
905         guint32 opts;
906         guint32 recompilation_times;
907 } CompileAllThreadArgs;
908
909 static void
910 compile_all_methods_thread_main_inner (CompileAllThreadArgs *args)
911 {
912         MonoAssembly *ass = args->ass;
913         int verbose = args->verbose;
914         MonoImage *image = mono_assembly_get_image (ass);
915         MonoMethod *method;
916         MonoCompile *cfg;
917         int i, count = 0, fail_count = 0;
918
919         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
920                 MonoError error;
921                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
922                 MonoMethodSignature *sig;
923
924                 if (mono_metadata_has_generic_params (image, token))
925                         continue;
926
927                 method = mono_get_method_checked (image, token, NULL, NULL, &error);
928                 if (!method) {
929                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
930                         continue;
931                 }
932                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
933                     (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
934                     (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
935                     (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
936                         continue;
937
938                 if (mono_class_is_gtd (method->klass))
939                         continue;
940                 sig = mono_method_signature (method);
941                 if (!sig) {
942                         char * desc = mono_method_full_name (method, TRUE);
943                         g_print ("Could not retrieve method signature for %s\n", desc);
944                         g_free (desc);
945                         fail_count ++;
946                         continue;
947                 }
948
949                 if (sig->has_type_parameters)
950                         continue;
951
952                 count++;
953                 if (verbose) {
954                         char * desc = mono_method_full_name (method, TRUE);
955                         g_print ("Compiling %d %s\n", count, desc);
956                         g_free (desc);
957                 }
958                 cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, args->opts), mono_get_root_domain (), (JitFlags)0, 0, -1);
959                 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
960                         printf ("Compilation of %s failed with exception '%s':\n", mono_method_full_name (cfg->method, TRUE), cfg->exception_message);
961                         fail_count ++;
962                 }
963                 mono_destroy_compile (cfg);
964         }
965
966         if (fail_count)
967                 exit (1);
968 }
969
970 static void
971 compile_all_methods_thread_main (CompileAllThreadArgs *args)
972 {
973         guint32 i;
974         for (i = 0; i < args->recompilation_times; ++i)
975                 compile_all_methods_thread_main_inner (args);
976 }
977
978 static void
979 compile_all_methods (MonoAssembly *ass, int verbose, guint32 opts, guint32 recompilation_times)
980 {
981         MonoError error;
982         CompileAllThreadArgs args;
983
984         args.ass = ass;
985         args.verbose = verbose;
986         args.opts = opts;
987         args.recompilation_times = recompilation_times;
988
989         /* 
990          * Need to create a mono thread since compilation might trigger
991          * running of managed code.
992          */
993         mono_thread_create_checked (mono_domain_get (), compile_all_methods_thread_main, &args, &error);
994         mono_error_assert_ok (&error);
995
996         mono_thread_manage ();
997 }
998
999 /**
1000  * mono_jit_exec:
1001  * @assembly: reference to an assembly
1002  * @argc: argument count
1003  * @argv: argument vector
1004  *
1005  * Start execution of a program.
1006  */
1007 int 
1008 mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])
1009 {
1010         MonoError error;
1011         MonoImage *image = mono_assembly_get_image (assembly);
1012         MonoMethod *method;
1013         guint32 entry = mono_image_get_entry_point (image);
1014
1015         if (!entry) {
1016                 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
1017                 /* FIXME: remove this silly requirement. */
1018                 mono_environment_exitcode_set (1);
1019                 return 1;
1020         }
1021
1022         method = mono_get_method_checked (image, entry, NULL, NULL, &error);
1023         if (method == NULL){
1024                 g_print ("The entry point method could not be loaded due to %s\n", mono_error_get_message (&error));
1025                 mono_error_cleanup (&error);
1026                 mono_environment_exitcode_set (1);
1027                 return 1;
1028         }
1029         
1030         if (mono_llvm_only) {
1031                 MonoObject *exc = NULL;
1032                 int res;
1033
1034                 res = mono_runtime_try_run_main (method, argc, argv, &exc);
1035                 if (exc) {
1036                         mono_unhandled_exception (exc);
1037                         mono_invoke_unhandled_exception_hook (exc);
1038                         g_assert_not_reached ();
1039                 }
1040                 return res;
1041         } else {
1042                 int res = mono_runtime_run_main_checked (method, argc, argv, &error);
1043                 if (!is_ok (&error)) {
1044                         MonoException *ex = mono_error_convert_to_exception (&error);
1045                         if (ex) {
1046                                 mono_unhandled_exception (&ex->object);
1047                                 mono_invoke_unhandled_exception_hook (&ex->object);
1048                                 g_assert_not_reached ();
1049                         }
1050                 }
1051                 return res;
1052         }
1053 }
1054
1055 typedef struct 
1056 {
1057         MonoDomain *domain;
1058         const char *file;
1059         int argc;
1060         char **argv;
1061         guint32 opts;
1062         char *aot_options;
1063 } MainThreadArgs;
1064
1065 static void main_thread_handler (gpointer user_data)
1066 {
1067         MainThreadArgs *main_args = (MainThreadArgs *)user_data;
1068         MonoAssembly *assembly;
1069
1070         if (mono_compile_aot) {
1071                 int i, res;
1072
1073                 /* Treat the other arguments as assemblies to compile too */
1074                 for (i = 0; i < main_args->argc; ++i) {
1075                         assembly = mono_domain_assembly_open (main_args->domain, main_args->argv [i]);
1076                         if (!assembly) {
1077                                 fprintf (stderr, "Can not open image %s\n", main_args->argv [i]);
1078                                 exit (1);
1079                         }
1080                         /* Check that the assembly loaded matches the filename */
1081                         {
1082                                 MonoImageOpenStatus status;
1083                                 MonoImage *img;
1084
1085                                 img = mono_image_open (main_args->argv [i], &status);
1086                                 if (img && strcmp (img->name, assembly->image->name)) {
1087                                         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);
1088                                         exit (1);
1089                                 }
1090                         }
1091                         res = mono_compile_assembly (assembly, main_args->opts, main_args->aot_options);
1092                         if (res != 0) {
1093                                 fprintf (stderr, "AOT of image %s failed.\n", main_args->argv [i]);
1094                                 exit (1);
1095                         }
1096                 }
1097         } else {
1098                 assembly = mono_domain_assembly_open (main_args->domain, main_args->file);
1099                 if (!assembly){
1100                         fprintf (stderr, "Can not open image %s\n", main_args->file);
1101                         exit (1);
1102                 }
1103
1104                 /* 
1105                  * This must be done in a thread managed by mono since it can invoke
1106                  * managed code.
1107                  */
1108                 if (main_args->opts & MONO_OPT_PRECOMP)
1109                         mono_precompile_assemblies ();
1110
1111                 mono_jit_exec (main_args->domain, assembly, main_args->argc, main_args->argv);
1112         }
1113 }
1114
1115 static int
1116 load_agent (MonoDomain *domain, char *desc)
1117 {
1118         MonoError error;
1119         char* col = strchr (desc, ':'); 
1120         char *agent, *args;
1121         MonoAssembly *agent_assembly;
1122         MonoImage *image;
1123         MonoMethod *method;
1124         guint32 entry;
1125         MonoArray *main_args;
1126         gpointer pa [1];
1127         MonoImageOpenStatus open_status;
1128
1129         if (col) {
1130                 agent = (char *)g_memdup (desc, col - desc + 1);
1131                 agent [col - desc] = '\0';
1132                 args = col + 1;
1133         } else {
1134                 agent = g_strdup (desc);
1135                 args = NULL;
1136         }
1137
1138         agent_assembly = mono_assembly_open (agent, &open_status);
1139         if (!agent_assembly) {
1140                 fprintf (stderr, "Cannot open agent assembly '%s': %s.\n", agent, mono_image_strerror (open_status));
1141                 g_free (agent);
1142                 return 2;
1143         }
1144
1145         /* 
1146          * Can't use mono_jit_exec (), as it sets things which might confuse the
1147          * real Main method.
1148          */
1149         image = mono_assembly_get_image (agent_assembly);
1150         entry = mono_image_get_entry_point (image);
1151         if (!entry) {
1152                 g_print ("Assembly '%s' doesn't have an entry point.\n", mono_image_get_filename (image));
1153                 g_free (agent);
1154                 return 1;
1155         }
1156
1157         method = mono_get_method_checked (image, entry, NULL, NULL, &error);
1158         if (method == NULL){
1159                 g_print ("The entry point method of assembly '%s' could not be loaded due to %s\n", agent, mono_error_get_message (&error));
1160                 mono_error_cleanup (&error);
1161                 g_free (agent);
1162                 return 1;
1163         }
1164         
1165         mono_thread_set_main (mono_thread_current ());
1166
1167         if (args) {
1168                 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 1, &error);
1169                 if (main_args)
1170                         mono_array_set (main_args, MonoString*, 0, mono_string_new (domain, args));
1171         } else {
1172                 main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 0, &error);
1173         }
1174         if (!main_args) {
1175                 g_print ("Could not allocate array for main args of assembly '%s' due to %s\n", agent, mono_error_get_message (&error));
1176                 mono_error_cleanup (&error);
1177                 g_free (agent);
1178                 return 1;
1179         }
1180         
1181
1182         pa [0] = main_args;
1183         /* Pass NULL as 'exc' so unhandled exceptions abort the runtime */
1184         mono_runtime_invoke_checked (method, NULL, pa, &error);
1185         if (!is_ok (&error)) {
1186                 g_print ("The entry point method of assembly '%s' could not execute due to %s\n", agent, mono_error_get_message (&error));
1187                 mono_error_cleanup (&error);
1188                 g_free (agent);
1189                 return 1;
1190         }
1191
1192         g_free (agent);
1193         return 0;
1194 }
1195
1196 static void
1197 mini_usage_jitdeveloper (void)
1198 {
1199         int i;
1200         
1201         fprintf (stdout,
1202                  "Runtime and JIT debugging options:\n"
1203                  "    --breakonex            Inserts a breakpoint on exceptions\n"
1204                  "    --break METHOD         Inserts a breakpoint at METHOD entry\n"
1205                  "    --break-at-bb METHOD N Inserts a breakpoint in METHOD at BB N\n"
1206                  "    --compile METHOD       Just compile METHOD in assembly\n"
1207                  "    --compile-all=N        Compiles all the methods in the assembly multiple times (default: 1)\n"
1208                  "    --ncompile N           Number of times to compile METHOD (default: 1)\n"
1209                  "    --print-vtable         Print the vtable of all used classes\n"
1210                  "    --regression           Runs the regression test contained in the assembly\n"
1211                  "    --single-method=OPTS   Runs regressions with only one method optimized with OPTS at any time\n"
1212                  "    --statfile FILE        Sets the stat file to FILE\n"
1213                  "    --stats                Print statistics about the JIT operations\n"
1214                  "    --wapi=hps|semdel|seminfo IO-layer maintenance\n"
1215                  "    --inject-async-exc METHOD OFFSET Inject an asynchronous exception at METHOD\n"
1216                  "    --verify-all           Run the verifier on all assemblies and methods\n"
1217                  "    --full-aot             Avoid JITting any code\n"
1218                  "    --llvmonly             Use LLVM compiled code only\n"
1219                  "    --agent=ASSEMBLY[:ARG] Loads the specific agent assembly and executes its Main method with the given argument before loading the main assembly.\n"
1220                  "    --no-x86-stack-align   Don't align stack on x86\n"
1221                  "\n"
1222                  "The options supported by MONO_DEBUG can also be passed on the command line.\n"
1223                  "\n"
1224                  "Other options:\n" 
1225                  "    --graph[=TYPE] METHOD  Draws a graph of the specified method:\n");
1226         
1227         for (i = 0; i < G_N_ELEMENTS (graph_names); ++i) {
1228                 fprintf (stdout, "                           %-10s %s\n", graph_names [i].name, graph_names [i].desc);
1229         }
1230 }
1231
1232 static void
1233 mini_usage_list_opt (void)
1234 {
1235         int i;
1236         
1237         for (i = 0; i < G_N_ELEMENTS (opt_names); ++i)
1238                 fprintf (stdout, "                           %-10s %s\n", optflag_get_name (i), optflag_get_desc (i));
1239 }
1240
1241 static void
1242 mini_usage (void)
1243 {
1244         fprintf (stdout,
1245                 "Usage is: mono [options] program [program-options]\n"
1246                 "\n"
1247                 "Development:\n"
1248                 "    --aot[=<options>]      Compiles the assembly to native code\n"
1249                 "    --debug[=<options>]    Enable debugging support, use --help-debug for details\n"
1250                 "    --debugger-agent=options Enable the debugger agent\n"
1251                 "    --profile[=profiler]   Runs in profiling mode with the specified profiler module\n"
1252                 "    --trace[=EXPR]         Enable tracing, use --help-trace for details\n"
1253                 "    --jitmap               Output a jit method map to /tmp/perf-PID.map\n"
1254                 "    --help-devel           Shows more options available to developers\n"
1255                 "\n"
1256                 "Runtime:\n"
1257                 "    --config FILE          Loads FILE as the Mono config\n"
1258                 "    --verbose, -v          Increases the verbosity level\n"
1259                 "    --help, -h             Show usage information\n"
1260                 "    --version, -V          Show version information\n"
1261                 "    --runtime=VERSION      Use the VERSION runtime, instead of autodetecting\n"
1262                 "    --optimize=OPT         Turns on or off a specific optimization\n"
1263                 "                           Use --list-opt to get a list of optimizations\n"
1264 #ifndef DISABLE_SECURITY
1265                 "    --security[=mode]      Turns on the unsupported security manager (off by default)\n"
1266                 "                           mode is one of cas, core-clr, verifiable or validil\n"
1267 #endif
1268                 "    --attach=OPTIONS       Pass OPTIONS to the attach agent in the runtime.\n"
1269                 "                           Currently the only supported option is 'disable'.\n"
1270                 "    --llvm, --nollvm       Controls whenever the runtime uses LLVM to compile code.\n"
1271                 "    --gc=[sgen,boehm]      Select SGen or Boehm GC (runs mono or mono-sgen)\n"
1272 #ifdef TARGET_OSX
1273                 "    --arch=[32,64]         Select architecture (runs mono32 or mono64)\n"
1274 #endif
1275 #ifdef HOST_WIN32
1276                 "    --mixed-mode           Enable mixed-mode image support.\n"
1277 #endif
1278                 "    --handlers             Install custom handlers, use --help-handlers for details.\n"
1279           );
1280 }
1281
1282 static void
1283 mini_trace_usage (void)
1284 {
1285         fprintf (stdout,
1286                  "Tracing options:\n"
1287                  "   --trace[=EXPR]        Trace every call, optional EXPR controls the scope\n"
1288                  "\n"
1289                  "EXPR is composed of:\n"
1290                  "    all                  All assemblies\n"
1291                  "    none                 No assemblies\n"
1292                  "    program              Entry point assembly\n"
1293                  "    assembly             Specifies an assembly\n"
1294                  "    wrapper              All wrappers bridging native and managed code\n"
1295                  "    M:Type:Method        Specifies a method\n"
1296                  "    N:Namespace          Specifies a namespace\n"
1297                  "    T:Type               Specifies a type\n"
1298                  "    E:Type               Specifies stack traces for an exception type\n"
1299                  "    EXPR                 Includes expression\n"
1300                  "    -EXPR                Excludes expression\n"
1301                  "    EXPR,EXPR            Multiple expressions\n"
1302                  "    disabled             Don't print any output until toggled via SIGUSR2\n");
1303 }
1304
1305 static void
1306 mini_debug_usage (void)
1307 {
1308         fprintf (stdout,
1309                  "Debugging options:\n"
1310                  "   --debug[=OPTIONS]     Enable debugging support, optional OPTIONS is a comma\n"
1311                  "                         separated list of options\n"
1312                  "\n"
1313                  "OPTIONS is composed of:\n"
1314                  "    casts                Enable more detailed InvalidCastException messages.\n"
1315                  "    mdb-optimizations    Disable some JIT optimizations which are normally\n"
1316                  "                         disabled when running inside the debugger.\n"
1317                  "                         This is useful if you plan to attach to the running\n"
1318                  "                         process with the debugger.\n");
1319 }
1320
1321 #if defined(MONO_ARCH_ARCHITECTURE)
1322 /* Redefine MONO_ARCHITECTURE to include more information */
1323 #undef MONO_ARCHITECTURE
1324 #define MONO_ARCHITECTURE MONO_ARCH_ARCHITECTURE
1325 #endif
1326
1327 static const char info[] =
1328 #ifdef HAVE_KW_THREAD
1329         "\tTLS:           __thread\n"
1330 #else
1331         "\tTLS:           normal\n"
1332 #endif /* HAVE_KW_THREAD */
1333 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
1334     "\tSIGSEGV:       altstack\n"
1335 #else
1336     "\tSIGSEGV:       normal\n"
1337 #endif
1338 #ifdef HAVE_EPOLL
1339     "\tNotifications: epoll\n"
1340 #elif defined(HAVE_KQUEUE)
1341     "\tNotification:  kqueue\n"
1342 #else
1343     "\tNotification:  Thread + polling\n"
1344 #endif
1345         "\tArchitecture:  " MONO_ARCHITECTURE "\n"
1346         "\tDisabled:      " DISABLED_FEATURES "\n"
1347         "\tMisc:          "
1348 #ifdef MONO_SMALL_CONFIG
1349         "smallconfig "
1350 #endif
1351 #ifdef MONO_BIG_ARRAYS
1352         "bigarrays "
1353 #endif
1354 #if defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) && !defined(DISABLE_SOFT_DEBUG)
1355         "softdebug "
1356 #endif
1357                 "\n"
1358 #ifdef MONO_ARCH_LLVM_SUPPORTED
1359 #ifdef ENABLE_LLVM
1360         "\tLLVM:          yes(" LLVM_VERSION ")\n"
1361 #else
1362         "\tLLVM:          supported, not enabled.\n"
1363 #endif
1364 #endif
1365         "";
1366
1367 #ifndef MONO_ARCH_AOT_SUPPORTED
1368 #define error_if_aot_unsupported() do {fprintf (stderr, "AOT compilation is not supported on this platform.\n"); exit (1);} while (0)
1369 #else
1370 #define error_if_aot_unsupported()
1371 #endif
1372
1373 static gboolean enable_debugging;
1374
1375 /*
1376  * mono_jit_parse_options:
1377  *
1378  *   Process the command line options in ARGV as done by the runtime executable. 
1379  * This should be called before mono_jit_init ().
1380  */
1381 void
1382 mono_jit_parse_options (int argc, char * argv[])
1383 {
1384         int i;
1385         char *trace_options = NULL;
1386         int mini_verbose = 0;
1387         guint32 opt;
1388
1389         /* 
1390          * Some options have no effect here, since they influence the behavior of 
1391          * mono_main ().
1392          */
1393
1394         opt = mono_parse_default_optimizations (NULL);
1395
1396         /* FIXME: Avoid code duplication */
1397         for (i = 0; i < argc; ++i) {
1398                 if (argv [i] [0] != '-')
1399                         break;
1400                 if (strncmp (argv [i], "--debugger-agent=", 17) == 0) {
1401                         MonoDebugOptions *opt = mini_get_debug_options ();
1402
1403                         mono_debugger_agent_parse_options (argv [i] + 17);
1404                         opt->mdb_optimizations = TRUE;
1405                         enable_debugging = TRUE;
1406                 } else if (!strcmp (argv [i], "--soft-breakpoints")) {
1407                         MonoDebugOptions *opt = mini_get_debug_options ();
1408
1409                         opt->soft_breakpoints = TRUE;
1410                         opt->explicit_null_checks = TRUE;
1411                 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
1412                         opt = parse_optimizations (opt, argv [i] + 11, TRUE);
1413                         mono_set_optimizations (opt);
1414                 } else if (strncmp (argv [i], "-O=", 3) == 0) {
1415                         opt = parse_optimizations (opt, argv [i] + 3, TRUE);
1416                         mono_set_optimizations (opt);
1417                 } else if (strcmp (argv [i], "--trace") == 0) {
1418                         trace_options = (char*)"";
1419                 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
1420                         trace_options = &argv [i][8];
1421                 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
1422                         mini_verbose++;
1423                 } else if (strcmp (argv [i], "--breakonex") == 0) {
1424                         MonoDebugOptions *opt = mini_get_debug_options ();
1425
1426                         opt->break_on_exc = TRUE;
1427                 } else if (strcmp (argv [i], "--stats") == 0) {
1428                         mono_counters_enable (-1);
1429                         mono_stats.enabled = TRUE;
1430                         mono_jit_stats.enabled = TRUE;
1431                 } else if (strcmp (argv [i], "--break") == 0) {
1432                         if (i+1 >= argc){
1433                                 fprintf (stderr, "Missing method name in --break command line option\n");
1434                                 exit (1);
1435                         }
1436                         
1437                         if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
1438                                 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
1439                 } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
1440                         mono_gc_params_set (argv[i] + 12);
1441                 } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
1442                         mono_gc_debug_set (argv[i] + 11);
1443                 } else if (strcmp (argv [i], "--llvm") == 0) {
1444 #ifndef MONO_ARCH_LLVM_SUPPORTED
1445                         fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
1446 #elif !defined(ENABLE_LLVM)
1447                         fprintf (stderr, "Mono Warning: --llvm not enabled in this runtime.\n");
1448 #else
1449                         mono_use_llvm = TRUE;
1450 #endif
1451                 } else if (argv [i][0] == '-' && argv [i][1] == '-' && mini_parse_debug_option (argv [i] + 2)) {
1452                 } else {
1453                         fprintf (stderr, "Unsupported command line option: '%s'\n", argv [i]);
1454                         exit (1);
1455                 }
1456         }
1457
1458         if (trace_options != NULL) {
1459                 /* 
1460                  * Need to call this before mini_init () so we can trace methods 
1461                  * compiled there too.
1462                  */
1463                 mono_jit_trace_calls = mono_trace_parse_options (trace_options);
1464                 if (mono_jit_trace_calls == NULL)
1465                         exit (1);
1466         }
1467
1468         if (mini_verbose)
1469                 mono_set_verbose_level (mini_verbose);
1470 }
1471
1472 static void
1473 mono_set_use_smp (int use_smp)
1474 {
1475 #if HAVE_SCHED_SETAFFINITY
1476         if (!use_smp) {
1477                 unsigned long proc_mask = 1;
1478 #ifdef GLIBC_BEFORE_2_3_4_SCHED_SETAFFINITY
1479                 sched_setaffinity (getpid(), (gpointer)&proc_mask);
1480 #else
1481                 sched_setaffinity (getpid(), sizeof (unsigned long), (const cpu_set_t *)&proc_mask);
1482 #endif
1483         }
1484 #endif
1485 }
1486
1487 static void
1488 switch_gc (char* argv[], const char* target_gc)
1489 {
1490         GString *path;
1491
1492         if (!strcmp (mono_gc_get_gc_name (), target_gc)) {
1493                 return;
1494         }
1495
1496         path = g_string_new (argv [0]);
1497
1498         /*Running mono without any argument*/
1499         if (strstr (argv [0], "-sgen"))
1500                 g_string_truncate (path, path->len - 5);
1501         else if (strstr (argv [0], "-boehm"))
1502                 g_string_truncate (path, path->len - 6);
1503
1504         g_string_append_c (path, '-');
1505         g_string_append (path, target_gc);
1506
1507 #ifdef HAVE_EXECVP
1508         execvp (path->str, argv);
1509         fprintf (stderr, "Error: Failed to switch to %s gc. mono-%s is not installed.\n", target_gc, target_gc);
1510 #else
1511         fprintf (stderr, "Error: --gc=<NAME> option not supported on this platform.\n");
1512 #endif
1513 }
1514
1515 #ifdef TARGET_OSX
1516
1517 /*
1518  * tries to increase the minimum number of files, if the number is below 1024
1519  */
1520 static void
1521 darwin_change_default_file_handles ()
1522 {
1523         struct rlimit limit;
1524         
1525         if (getrlimit (RLIMIT_NOFILE, &limit) == 0){
1526                 if (limit.rlim_cur < 1024){
1527                         limit.rlim_cur = MAX(1024,limit.rlim_cur);
1528                         setrlimit (RLIMIT_NOFILE, &limit);
1529                 }
1530         }
1531 }
1532
1533 static void
1534 switch_arch (char* argv[], const char* target_arch)
1535 {
1536         GString *path;
1537         gsize arch_offset;
1538
1539         if ((strcmp (target_arch, "32") == 0 && strcmp (MONO_ARCHITECTURE, "x86") == 0) ||
1540                 (strcmp (target_arch, "64") == 0 && strcmp (MONO_ARCHITECTURE, "amd64") == 0)) {
1541                 return; /* matching arch loaded */
1542         }
1543
1544         path = g_string_new (argv [0]);
1545         arch_offset = path->len -2; /* last two characters */
1546
1547         /* Remove arch suffix if present */
1548         if (strstr (&path->str[arch_offset], "32") || strstr (&path->str[arch_offset], "64")) {
1549                 g_string_truncate (path, arch_offset);
1550         }
1551
1552         g_string_append (path, target_arch);
1553
1554         if (execvp (path->str, argv) < 0) {
1555                 fprintf (stderr, "Error: --arch=%s Failed to switch to '%s'.\n", target_arch, path->str);
1556                 exit (1);
1557         }
1558 }
1559
1560 #endif
1561
1562 #define MONO_HANDLERS_ARGUMENT "--handlers="
1563 #define MONO_HANDLERS_ARGUMENT_LEN G_N_ELEMENTS(MONO_HANDLERS_ARGUMENT)-1
1564
1565 /**
1566  * mono_main:
1567  * @argc: number of arguments in the argv array
1568  * @argv: array of strings containing the startup arguments
1569  *
1570  * Launches the Mono JIT engine and parses all the command line options
1571  * in the same way that the mono command line VM would.
1572  */
1573 int
1574 mono_main (int argc, char* argv[])
1575 {
1576         MainThreadArgs main_args;
1577         MonoAssembly *assembly;
1578         MonoMethodDesc *desc;
1579         MonoMethod *method;
1580         MonoCompile *cfg;
1581         MonoDomain *domain;
1582         MonoImageOpenStatus open_status;
1583         const char* aname, *mname = NULL;
1584         char *config_file = NULL;
1585         int i, count = 1;
1586         guint32 opt, action = DO_EXEC, recompilation_times = 1;
1587         MonoGraphOptions mono_graph_options = (MonoGraphOptions)0;
1588         int mini_verbose = 0;
1589         gboolean enable_profile = FALSE;
1590         char *trace_options = NULL;
1591         char *profile_options = NULL;
1592         char *aot_options = NULL;
1593         char *forced_version = NULL;
1594         GPtrArray *agents = NULL;
1595         char *attach_options = NULL;
1596 #ifdef MONO_JIT_INFO_TABLE_TEST
1597         int test_jit_info_table = FALSE;
1598 #endif
1599 #ifdef HOST_WIN32
1600         int mixed_mode = FALSE;
1601 #endif
1602 #ifdef __native_client__
1603         gboolean nacl_null_checks_off = FALSE;
1604 #endif
1605
1606 #ifdef MOONLIGHT
1607 #ifndef HOST_WIN32
1608         /* stdout defaults to block buffering if it's not writing to a terminal, which
1609          * happens with our test harness: we redirect stdout to capture it. Force line
1610          * buffering in all cases. */
1611         setlinebuf (stdout);
1612 #endif
1613 #endif
1614
1615         setlocale (LC_ALL, "");
1616
1617 #if TARGET_OSX
1618         darwin_change_default_file_handles ();
1619 #endif
1620
1621         if (g_getenv ("MONO_NO_SMP"))
1622                 mono_set_use_smp (FALSE);
1623         
1624         g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
1625         g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
1626
1627         opt = mono_parse_default_optimizations (NULL);
1628
1629         for (i = 1; i < argc; ++i) {
1630                 if (argv [i] [0] != '-')
1631                         break;
1632                 if (strcmp (argv [i], "--regression") == 0) {
1633                         action = DO_REGRESSION;
1634                 } else if (strncmp (argv [i], "--single-method=", 16) == 0) {
1635                         char *full_opts = g_strdup_printf ("-all,%s", argv [i] + 16);
1636                         action = DO_SINGLE_METHOD_REGRESSION;
1637                         mono_single_method_regression_opt = parse_optimizations (opt, full_opts, TRUE);
1638                         g_free (full_opts);
1639                 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
1640                         mini_verbose++;
1641                 } else if (strcmp (argv [i], "--version") == 0 || strcmp (argv [i], "-V") == 0) {
1642                         char *build = mono_get_runtime_build_info ();
1643                         char *gc_descr;
1644
1645                         g_print ("Mono JIT compiler version %s\nCopyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com\n", build);
1646                         g_free (build);
1647                         g_print (info);
1648                         gc_descr = mono_gc_get_description ();
1649                         g_print ("\tGC:            %s\n", gc_descr);
1650                         g_free (gc_descr);
1651                         return 0;
1652                 } else if (strcmp (argv [i], "--help") == 0 || strcmp (argv [i], "-h") == 0) {
1653                         mini_usage ();
1654                         return 0;
1655                 } else if (strcmp (argv [i], "--help-trace") == 0){
1656                         mini_trace_usage ();
1657                         return 0;
1658                 } else if (strcmp (argv [i], "--help-devel") == 0){
1659                         mini_usage_jitdeveloper ();
1660                         return 0;
1661                 } else if (strcmp (argv [i], "--help-debug") == 0){
1662                         mini_debug_usage ();
1663                         return 0;
1664                 } else if (strcmp (argv [i], "--list-opt") == 0){
1665                         mini_usage_list_opt ();
1666                         return 0;
1667                 } else if (strncmp (argv [i], "--statfile", 10) == 0) {
1668                         if (i + 1 >= argc){
1669                                 fprintf (stderr, "error: --statfile requires a filename argument\n");
1670                                 return 1;
1671                         }
1672                         mini_stats_fd = fopen (argv [++i], "w+");
1673                 } else if (strncmp (argv [i], "--optimize=", 11) == 0) {
1674                         opt = parse_optimizations (opt, argv [i] + 11, TRUE);
1675                 } else if (strncmp (argv [i], "-O=", 3) == 0) {
1676                         opt = parse_optimizations (opt, argv [i] + 3, TRUE);
1677                 } else if (strncmp (argv [i], "--bisect=", 9) == 0) {
1678                         char *param = argv [i] + 9;
1679                         char *sep = strchr (param, ':');
1680                         if (!sep) {
1681                                 fprintf (stderr, "Error: --bisect requires OPT:FILENAME\n");
1682                                 return 1;
1683                         }
1684                         char *opt_string = g_strndup (param, sep - param);
1685                         guint32 opt = parse_optimizations (0, opt_string, FALSE);
1686                         g_free (opt_string);
1687                         mono_set_bisect_methods (opt, sep + 1);
1688                 } else if (strcmp (argv [i], "--gc=sgen") == 0) {
1689                         switch_gc (argv, "sgen");
1690                 } else if (strcmp (argv [i], "--gc=boehm") == 0) {
1691                         switch_gc (argv, "boehm");
1692                 } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
1693                         mono_gc_params_set (argv[i] + 12);
1694                 } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
1695                         mono_gc_debug_set (argv[i] + 11);
1696                 }
1697 #ifdef TARGET_OSX
1698                 else if (strcmp (argv [i], "--arch=32") == 0) {
1699                         switch_arch (argv, "32");
1700                 } else if (strcmp (argv [i], "--arch=64") == 0) {
1701                         switch_arch (argv, "64");
1702                 }
1703 #endif
1704                 else if (strcmp (argv [i], "--config") == 0) {
1705                         if (i +1 >= argc){
1706                                 fprintf (stderr, "error: --config requires a filename argument\n");
1707                                 return 1;
1708                         }
1709                         config_file = argv [++i];
1710 #ifdef HOST_WIN32
1711                 } else if (strcmp (argv [i], "--mixed-mode") == 0) {
1712                         mixed_mode = TRUE;
1713 #endif
1714                 } else if (strcmp (argv [i], "--ncompile") == 0) {
1715                         if (i + 1 >= argc){
1716                                 fprintf (stderr, "error: --ncompile requires an argument\n");
1717                                 return 1;
1718                         }
1719                         count = atoi (argv [++i]);
1720                         action = DO_BENCH;
1721                 } else if (strcmp (argv [i], "--trace") == 0) {
1722                         trace_options = (char*)"";
1723                 } else if (strncmp (argv [i], "--trace=", 8) == 0) {
1724                         trace_options = &argv [i][8];
1725                 } else if (strcmp (argv [i], "--breakonex") == 0) {
1726                         MonoDebugOptions *opt = mini_get_debug_options ();
1727
1728                         opt->break_on_exc = TRUE;
1729                 } else if (strcmp (argv [i], "--break") == 0) {
1730                         if (i+1 >= argc){
1731                                 fprintf (stderr, "Missing method name in --break command line option\n");
1732                                 return 1;
1733                         }
1734                         
1735                         if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
1736                                 fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
1737                 } else if (strcmp (argv [i], "--break-at-bb") == 0) {
1738                         if (i + 2 >= argc) {
1739                                 fprintf (stderr, "Missing method name or bb num in --break-at-bb command line option.");
1740                                 return 1;
1741                         }
1742                         mono_break_at_bb_method = mono_method_desc_new (argv [++i], TRUE);
1743                         if (mono_break_at_bb_method == NULL) {
1744                                 fprintf (stderr, "Method name is in a bad format in --break-at-bb command line option.");
1745                                 return 1;
1746                         }
1747                         mono_break_at_bb_bb_num = atoi (argv [++i]);
1748                 } else if (strcmp (argv [i], "--inject-async-exc") == 0) {
1749                         if (i + 2 >= argc) {
1750                                 fprintf (stderr, "Missing method name or position in --inject-async-exc command line option\n");
1751                                 return 1;
1752                         }
1753                         mono_inject_async_exc_method = mono_method_desc_new (argv [++i], TRUE);
1754                         if (mono_inject_async_exc_method == NULL) {
1755                                 fprintf (stderr, "Method name is in a bad format in --inject-async-exc command line option\n");
1756                                 return 1;
1757                         }
1758                         mono_inject_async_exc_pos = atoi (argv [++i]);
1759                 } else if (strcmp (argv [i], "--verify-all") == 0) {
1760                         mono_verifier_enable_verify_all ();
1761                 } else if (strcmp (argv [i], "--full-aot") == 0) {
1762                         mono_jit_set_aot_mode (MONO_AOT_MODE_FULL);
1763                 } else if (strcmp (argv [i], "--llvmonly") == 0) {
1764                         mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY);
1765                 } else if (strcmp (argv [i], "--hybrid-aot") == 0) {
1766                         mono_jit_set_aot_mode (MONO_AOT_MODE_HYBRID);
1767                 } else if (strcmp (argv [i], "--print-vtable") == 0) {
1768                         mono_print_vtable = TRUE;
1769                 } else if (strcmp (argv [i], "--stats") == 0) {
1770                         mono_counters_enable (-1);
1771                         mono_stats.enabled = TRUE;
1772                         mono_jit_stats.enabled = TRUE;
1773 #ifndef DISABLE_AOT
1774                 } else if (strcmp (argv [i], "--aot") == 0) {
1775                         error_if_aot_unsupported ();
1776                         mono_compile_aot = TRUE;
1777                 } else if (strncmp (argv [i], "--aot=", 6) == 0) {
1778                         error_if_aot_unsupported ();
1779                         mono_compile_aot = TRUE;
1780                         aot_options = &argv [i][6];
1781 #endif
1782                 } else if (strncmp (argv [i], "--compile-all=", 14) == 0) {
1783                         action = DO_COMPILE;
1784                         recompilation_times = atoi (argv [i] + 14);
1785                 } else if (strcmp (argv [i], "--compile-all") == 0) {
1786                         action = DO_COMPILE;
1787                 } else if (strncmp (argv [i], "--runtime=", 10) == 0) {
1788                         forced_version = &argv [i][10];
1789                 } else if (strcmp (argv [i], "--jitmap") == 0) {
1790                         mono_enable_jit_map ();
1791                 } else if (strcmp (argv [i], "--profile") == 0) {
1792                         enable_profile = TRUE;
1793                         profile_options = NULL;
1794                 } else if (strncmp (argv [i], "--profile=", 10) == 0) {
1795                         enable_profile = TRUE;
1796                         profile_options = argv [i] + 10;
1797                 } else if (strncmp (argv [i], "--agent=", 8) == 0) {
1798                         if (agents == NULL)
1799                                 agents = g_ptr_array_new ();
1800                         g_ptr_array_add (agents, argv [i] + 8);
1801                 } else if (strncmp (argv [i], "--attach=", 9) == 0) {
1802                         attach_options = argv [i] + 9;
1803                 } else if (strcmp (argv [i], "--compile") == 0) {
1804                         if (i + 1 >= argc){
1805                                 fprintf (stderr, "error: --compile option requires a method name argument\n");
1806                                 return 1;
1807                         }
1808                         
1809                         mname = argv [++i];
1810                         action = DO_BENCH;
1811                 } else if (strncmp (argv [i], "--graph=", 8) == 0) {
1812                         if (i + 1 >= argc){
1813                                 fprintf (stderr, "error: --graph option requires a method name argument\n");
1814                                 return 1;
1815                         }
1816                         
1817                         mono_graph_options = mono_parse_graph_options (argv [i] + 8);
1818                         mname = argv [++i];
1819                         action = DO_DRAW;
1820                 } else if (strcmp (argv [i], "--graph") == 0) {
1821                         if (i + 1 >= argc){
1822                                 fprintf (stderr, "error: --graph option requires a method name argument\n");
1823                                 return 1;
1824                         }
1825                         
1826                         mname = argv [++i];
1827                         mono_graph_options = MONO_GRAPH_CFG;
1828                         action = DO_DRAW;
1829                 } else if (strcmp (argv [i], "--debug") == 0) {
1830                         enable_debugging = TRUE;
1831                 } else if (strncmp (argv [i], "--debug=", 8) == 0) {
1832                         enable_debugging = TRUE;
1833                         if (!parse_debug_options (argv [i] + 8))
1834                                 return 1;
1835                 } else if (strncmp (argv [i], "--debugger-agent=", 17) == 0) {
1836                         MonoDebugOptions *opt = mini_get_debug_options ();
1837
1838                         mono_debugger_agent_parse_options (argv [i] + 17);
1839                         opt->mdb_optimizations = TRUE;
1840                         enable_debugging = TRUE;
1841                 } else if (strcmp (argv [i], "--security") == 0) {
1842 #ifndef DISABLE_SECURITY
1843                         mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
1844 #else
1845                         fprintf (stderr, "error: --security: not compiled with security manager support");
1846                         return 1;
1847 #endif
1848                 } else if (strncmp (argv [i], "--security=", 11) == 0) {
1849                         /* Note: validil, and verifiable need to be
1850                            accepted even if DISABLE_SECURITY is defined. */
1851
1852                         if (strcmp (argv [i] + 11, "core-clr") == 0) {
1853 #ifndef DISABLE_SECURITY
1854                                 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
1855                                 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
1856 #else
1857                                 fprintf (stderr, "error: --security: not compiled with CoreCLR support");
1858                                 return 1;
1859 #endif
1860                         } else if (strcmp (argv [i] + 11, "core-clr-test") == 0) {
1861 #ifndef DISABLE_SECURITY
1862                                 /* fixme should we enable verifiable code here?*/
1863                                 mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
1864                                 mono_security_core_clr_test = TRUE;
1865 #else
1866                                 fprintf (stderr, "error: --security: not compiled with CoreCLR support");
1867                                 return 1;
1868 #endif
1869                         } else if (strcmp (argv [i] + 11, "cas") == 0) {
1870 #ifndef DISABLE_SECURITY
1871                                 fprintf (stderr, "warning: --security=cas not supported.");
1872 #else
1873                                 fprintf (stderr, "error: --security: not compiled with CAS support");
1874                                 return 1;
1875 #endif
1876                         } else if (strcmp (argv [i] + 11, "validil") == 0) {
1877                                 mono_verifier_set_mode (MONO_VERIFIER_MODE_VALID);
1878                         } else if (strcmp (argv [i] + 11, "verifiable") == 0) {
1879                                 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
1880                         } else {
1881                                 fprintf (stderr, "error: --security= option has invalid argument (cas, core-clr, verifiable or validil)\n");
1882                                 return 1;
1883                         }
1884                 } else if (strcmp (argv [i], "--desktop") == 0) {
1885                         mono_gc_set_desktop_mode ();
1886                         /* Put more desktop-specific optimizations here */
1887                 } else if (strcmp (argv [i], "--server") == 0){
1888                         mono_config_set_server_mode (TRUE);
1889                         /* Put more server-specific optimizations here */
1890                 } else if (strcmp (argv [i], "--inside-mdb") == 0) {
1891                         action = DO_DEBUGGER;
1892                 } else if (strncmp (argv [i], "--wapi=", 7) == 0) {
1893                         fprintf (stderr, "--wapi= option no longer supported\n.");
1894                         return 1;
1895                 } else if (strcmp (argv [i], "--no-x86-stack-align") == 0) {
1896                         mono_do_x86_stack_align = FALSE;
1897 #ifdef MONO_JIT_INFO_TABLE_TEST
1898                 } else if (strcmp (argv [i], "--test-jit-info-table") == 0) {
1899                         test_jit_info_table = TRUE;
1900 #endif
1901                 } else if (strcmp (argv [i], "--llvm") == 0) {
1902 #ifndef MONO_ARCH_LLVM_SUPPORTED
1903                         fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
1904 #elif !defined(ENABLE_LLVM)
1905                         fprintf (stderr, "Mono Warning: --llvm not enabled in this runtime.\n");
1906 #else
1907                         mono_use_llvm = TRUE;
1908 #endif
1909                 } else if (strcmp (argv [i], "--nollvm") == 0){
1910                         mono_use_llvm = FALSE;
1911 #ifdef __native_client__
1912                 } else if (strcmp (argv [i], "--nacl-mono-path") == 0){
1913                         nacl_mono_path = g_strdup(argv[++i]);
1914                 } else if (strcmp (argv [i], "--nacl-null-checks-off") == 0){
1915                         nacl_null_checks_off = TRUE;
1916 #endif
1917                 } else if (strncmp (argv [i], MONO_HANDLERS_ARGUMENT, MONO_HANDLERS_ARGUMENT_LEN) == 0) {
1918                         //Install specific custom handlers.
1919                         if (!mono_runtime_install_custom_handlers (argv[i] + MONO_HANDLERS_ARGUMENT_LEN)) {
1920                                 fprintf (stderr, "error: " MONO_HANDLERS_ARGUMENT ", one or more unknown handlers: '%s'\n", argv [i]);
1921                                 return 1;
1922                         }
1923                 } else if (strcmp (argv [i], "--help-handlers") == 0) {
1924                         mono_runtime_install_custom_handlers_usage ();
1925                         return 0;
1926                 } else if (argv [i][0] == '-' && argv [i][1] == '-' && mini_parse_debug_option (argv [i] + 2)) {
1927                 } else {
1928                         fprintf (stderr, "Unknown command line option: '%s'\n", argv [i]);
1929                         return 1;
1930                 }
1931         }
1932
1933 #ifdef __native_client_codegen__
1934         if (!nacl_null_checks_off) {
1935                 MonoDebugOptions *opt = mini_get_debug_options ();
1936                 opt->explicit_null_checks = TRUE;
1937         }
1938 #endif
1939
1940 #if defined(DISABLE_HW_TRAPS) || defined(MONO_ARCH_DISABLE_HW_TRAPS)
1941         // Signal handlers not available
1942         {
1943                 MonoDebugOptions *opt = mini_get_debug_options ();
1944                 opt->explicit_null_checks = TRUE;
1945         }
1946 #endif
1947
1948         if (!argv [i]) {
1949                 mini_usage ();
1950                 return 1;
1951         }
1952
1953 #if !defined(HOST_WIN32) && defined(HAVE_UNISTD_H)
1954         /*
1955          * If we are not embedded, use the mono runtime executable to run managed exe's.
1956          */
1957         {
1958                 char *runtime_path;
1959
1960                 runtime_path = mono_w32process_get_path (getpid ());
1961                 if (runtime_path) {
1962                         mono_w32process_set_cli_launcher (runtime_path);
1963                         g_free (runtime_path);
1964                 }
1965         }
1966 #endif
1967
1968         if (g_getenv ("MONO_XDEBUG"))
1969                 enable_debugging = TRUE;
1970
1971 #ifdef MONO_CROSS_COMPILE
1972        if (!mono_compile_aot) {
1973                    fprintf (stderr, "This mono runtime is compiled for cross-compiling. Only the --aot option is supported.\n");
1974                    exit (1);
1975        }
1976 #if SIZEOF_VOID_P == 8 && (defined(TARGET_ARM) || defined(TARGET_X86))
1977        fprintf (stderr, "Can't cross-compile on 64-bit platforms to 32-bit architecture.\n");
1978        exit (1);
1979 #elif SIZEOF_VOID_P == 4 && (defined(TARGET_ARM64) || defined(TARGET_AMD64))
1980        fprintf (stderr, "Can't cross-compile on 32-bit platforms to 64-bit architecture.\n");
1981        exit (1);
1982 #endif
1983 #endif
1984
1985         if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
1986                 g_set_prgname (argv[i]);
1987         }
1988
1989         mono_counters_init ();
1990
1991 #ifndef HOST_WIN32
1992         mono_w32handle_init ();
1993 #endif
1994
1995         /* Set rootdir before loading config */
1996         mono_set_rootdir ();
1997
1998         if (enable_profile) {
1999                 mono_profiler_load (profile_options);
2000                 mono_profiler_thread_name (MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ()), "Main");
2001         }
2002
2003         mono_attach_parse_options (attach_options);
2004
2005         if (trace_options != NULL){
2006                 /* 
2007                  * Need to call this before mini_init () so we can trace methods 
2008                  * compiled there too.
2009                  */
2010                 mono_jit_trace_calls = mono_trace_parse_options (trace_options);
2011                 if (mono_jit_trace_calls == NULL)
2012                         exit (1);
2013         }
2014
2015 #ifdef DISABLE_JIT
2016         if (!mono_aot_only) {
2017                 fprintf (stderr, "This runtime has been configured with --enable-minimal=jit, so the --full-aot command line option is required.\n");
2018                 exit (1);
2019         }
2020 #endif
2021
2022         if (action == DO_DEBUGGER) {
2023                 enable_debugging = TRUE;
2024                 g_print ("The Mono Debugger is no longer supported.\n");
2025                 return 1;
2026         } else if (enable_debugging)
2027                 mono_debug_init (MONO_DEBUG_FORMAT_MONO);
2028
2029 #ifdef HOST_WIN32
2030         if (mixed_mode)
2031                 mono_load_coree (argv [i]);
2032 #endif
2033
2034         /* Parse gac loading options before loading assemblies. */
2035         if (mono_compile_aot || action == DO_EXEC || action == DO_DEBUGGER) {
2036                 mono_config_parse (config_file);
2037         }
2038
2039         mono_set_defaults (mini_verbose, opt);
2040         domain = mini_init (argv [i], forced_version);
2041
2042         mono_gc_set_stack_end (&domain);
2043
2044         if (agents) {
2045                 int i;
2046
2047                 for (i = 0; i < agents->len; ++i) {
2048                         int res = load_agent (domain, (char*)g_ptr_array_index (agents, i));
2049                         if (res) {
2050                                 g_ptr_array_free (agents, TRUE);
2051                                 mini_cleanup (domain);
2052                                 return 1;
2053                         }
2054                 }
2055
2056                 g_ptr_array_free (agents, TRUE);
2057         }
2058         
2059         switch (action) {
2060         case DO_SINGLE_METHOD_REGRESSION:
2061                 mono_do_single_method_regression = TRUE;
2062         case DO_REGRESSION:
2063                 if (mini_regression_list (mini_verbose, argc -i, argv + i)) {
2064                         g_print ("Regression ERRORS!\n");
2065                         mini_cleanup (domain);
2066                         return 1;
2067                 }
2068                 mini_cleanup (domain);
2069                 return 0;
2070         case DO_BENCH:
2071                 if (argc - i != 1 || mname == NULL) {
2072                         g_print ("Usage: mini --ncompile num --compile method assembly\n");
2073                         mini_cleanup (domain);
2074                         return 1;
2075                 }
2076                 aname = argv [i];
2077                 break;
2078         case DO_COMPILE:
2079                 if (argc - i != 1) {
2080                         mini_usage ();
2081                         mini_cleanup (domain);
2082                         return 1;
2083                 }
2084                 aname = argv [i];
2085                 break;
2086         case DO_DRAW:
2087                 if (argc - i != 1 || mname == NULL) {
2088                         mini_usage ();
2089                         mini_cleanup (domain);
2090                         return 1;
2091                 }
2092                 aname = argv [i];
2093                 break;
2094         default:
2095                 if (argc - i < 1) {
2096                         mini_usage ();
2097                         mini_cleanup (domain);
2098                         return 1;
2099                 }
2100                 aname = argv [i];
2101                 break;
2102         }
2103
2104 #ifdef MONO_JIT_INFO_TABLE_TEST
2105         if (test_jit_info_table)
2106                 jit_info_table_test (domain);
2107 #endif
2108
2109         assembly = mono_assembly_open (aname, &open_status);
2110         if (!assembly) {
2111                 fprintf (stderr, "Cannot open assembly '%s': %s.\n", aname, mono_image_strerror (open_status));
2112                 mini_cleanup (domain);
2113                 return 2;
2114         }
2115
2116         if (trace_options != NULL)
2117                 mono_trace_set_assembly (assembly);
2118
2119         if (mono_compile_aot || action == DO_EXEC) {
2120                 const char *error;
2121
2122                 //mono_set_rootdir ();
2123
2124                 error = mono_check_corlib_version ();
2125                 if (error) {
2126                         fprintf (stderr, "Corlib not in sync with this runtime: %s\n", error);
2127                         fprintf (stderr, "Loaded from: %s\n",
2128                                 mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown");
2129                         fprintf (stderr, "Download a newer corlib or a newer runtime at http://www.mono-project.com/download.\n");
2130                         exit (1);
2131                 }
2132
2133 #if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
2134                 /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
2135                 if (!enable_debugging && !mono_compile_aot && ((MonoCLIImageInfo*)(mono_assembly_get_image (assembly)->image_info))->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
2136                         FreeConsole ();
2137 #endif
2138
2139                 main_args.domain = domain;
2140                 main_args.file = aname;         
2141                 main_args.argc = argc - i;
2142                 main_args.argv = argv + i;
2143                 main_args.opts = opt;
2144                 main_args.aot_options = aot_options;
2145 #if RUN_IN_SUBTHREAD
2146                 mono_runtime_exec_managed_code (domain, main_thread_handler, &main_args);
2147 #else
2148                 main_thread_handler (&main_args);
2149                 mono_thread_manage ();
2150 #endif
2151
2152                 mini_cleanup (domain);
2153
2154                 /* Look up return value from System.Environment.ExitCode */
2155                 i = mono_environment_exitcode_get ();
2156                 return i;
2157         } else if (action == DO_COMPILE) {
2158                 compile_all_methods (assembly, mini_verbose, opt, recompilation_times);
2159                 mini_cleanup (domain);
2160                 return 0;
2161         } else if (action == DO_DEBUGGER) {
2162                 return 1;
2163         }
2164         desc = mono_method_desc_new (mname, 0);
2165         if (!desc) {
2166                 g_print ("Invalid method name %s\n", mname);
2167                 mini_cleanup (domain);
2168                 return 3;
2169         }
2170         method = mono_method_desc_search_in_image (desc, mono_assembly_get_image (assembly));
2171         if (!method) {
2172                 g_print ("Cannot find method %s\n", mname);
2173                 mini_cleanup (domain);
2174                 return 3;
2175         }
2176
2177 #ifndef DISABLE_JIT
2178         if (action == DO_DRAW) {
2179                 int part = 0;
2180
2181                 switch (mono_graph_options) {
2182                 case MONO_GRAPH_DTREE:
2183                         part = 1;
2184                         opt |= MONO_OPT_LOOP;
2185                         break;
2186                 case MONO_GRAPH_CFG_CODE:
2187                         part = 1;
2188                         break;
2189                 case MONO_GRAPH_CFG_SSA:
2190                         part = 2;
2191                         break;
2192                 case MONO_GRAPH_CFG_OPTCODE:
2193                         part = 3;
2194                         break;
2195                 default:
2196                         break;
2197                 }
2198
2199                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2200                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
2201                         MonoMethod *nm;
2202                         nm = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
2203                         cfg = mini_method_compile (nm, opt, mono_get_root_domain (), (JitFlags)0, part, -1);
2204                 }
2205                 else
2206                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, part, -1);
2207                 if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
2208                         g_warning ("no SSA info available (use -O=deadce)");
2209                         return 1;
2210                 }
2211                 mono_draw_graph (cfg, mono_graph_options);
2212                 mono_destroy_compile (cfg);
2213
2214         } else if (action == DO_BENCH) {
2215                 if (mini_stats_fd) {
2216                         const char *n;
2217                         double no_opt_time = 0.0;
2218                         GTimer *timer = g_timer_new ();
2219                         fprintf (mini_stats_fd, "$stattitle = \'Compilations times for %s\';\n", 
2220                                  mono_method_full_name (method, TRUE));
2221                         fprintf (mini_stats_fd, "@data = (\n");
2222                         fprintf (mini_stats_fd, "[");
2223                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
2224                                 opt = opt_sets [i];
2225                                 n = mono_opt_descr (opt);
2226                                 if (!n [0])
2227                                         n = "none";
2228                                 fprintf (mini_stats_fd, "\"%s\",", n);
2229                         }
2230                         fprintf (mini_stats_fd, "],\n[");
2231
2232                         for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) {
2233                                 int j;
2234                                 double elapsed;
2235                                 opt = opt_sets [i];
2236                                 g_timer_start (timer);
2237                                 for (j = 0; j < count; ++j) {
2238                                         cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2239                                         mono_destroy_compile (cfg);
2240                                 }
2241                                 g_timer_stop (timer);
2242                                 elapsed = g_timer_elapsed (timer, NULL);
2243                                 if (!opt)
2244                                         no_opt_time = elapsed;
2245                                 fprintf (mini_stats_fd, "%f, ", elapsed);
2246                         }
2247                         fprintf (mini_stats_fd, "]");
2248                         if (no_opt_time > 0.0) {
2249                                 fprintf (mini_stats_fd, ", \n[");
2250                                 for (i = 0; i < G_N_ELEMENTS (opt_sets); i++) 
2251                                         fprintf (mini_stats_fd, "%f,", no_opt_time);
2252                                 fprintf (mini_stats_fd, "]");
2253                         }
2254                         fprintf (mini_stats_fd, ");\n");
2255                 } else {
2256                         for (i = 0; i < count; ++i) {
2257                                 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2258                                         (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
2259                                         method = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
2260
2261                                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2262                                 mono_destroy_compile (cfg);
2263                         }
2264                 }
2265         } else {
2266                 cfg = mini_method_compile (method, opt, mono_get_root_domain (), (JitFlags)0, 0, -1);
2267                 mono_destroy_compile (cfg);
2268         }
2269 #endif
2270
2271         mini_cleanup (domain);
2272         return 0;
2273 }
2274
2275 MonoDomain * 
2276 mono_jit_init (const char *file)
2277 {
2278         return mini_init (file, NULL);
2279 }
2280
2281 /**
2282  * mono_jit_init_version:
2283  * @domain_name: the name of the root domain
2284  * @runtime_version: the version of the runtime to load
2285  *
2286  * Use this version when you want to force a particular runtime
2287  * version to be used.  By default Mono will pick the runtime that is
2288  * referenced by the initial assembly (specified in @file), this
2289  * routine allows programmers to specify the actual runtime to be used
2290  * as the initial runtime is inherited by all future assemblies loaded
2291  * (since Mono does not support having more than one mscorlib runtime
2292  * loaded at once).
2293  *
2294  * The @runtime_version can be one of these strings: "v4.0.30319" for
2295  * desktop, "mobile" for mobile or "moonlight" for Silverlight compat.
2296  * If an unrecognized string is input, the vm will default to desktop.
2297  *
2298  * Returns: the MonoDomain representing the domain where the assembly
2299  * was loaded.
2300  */
2301 MonoDomain * 
2302 mono_jit_init_version (const char *domain_name, const char *runtime_version)
2303 {
2304         return mini_init (domain_name, runtime_version);
2305 }
2306
2307 void        
2308 mono_jit_cleanup (MonoDomain *domain)
2309 {
2310         mono_thread_manage ();
2311
2312         mini_cleanup (domain);
2313 }
2314
2315 void
2316 mono_jit_set_aot_only (gboolean val)
2317 {
2318         mono_aot_only = val;
2319 }
2320
2321 void
2322 mono_jit_set_aot_mode (MonoAotMode mode)
2323 {
2324         /* we don't want to set mono_aot_mode twice */
2325         g_assert (mono_aot_mode == MONO_AOT_MODE_NONE);
2326         mono_aot_mode = mode;
2327
2328         if (mono_aot_mode == MONO_AOT_MODE_LLVMONLY) {
2329                 mono_aot_only = TRUE;
2330                 mono_llvm_only = TRUE;
2331         }
2332         if (mono_aot_mode == MONO_AOT_MODE_FULL) {
2333                 mono_aot_only = TRUE;
2334         }
2335         if (mono_aot_mode == MONO_AOT_MODE_HYBRID) {
2336                 mono_set_generic_sharing_vt_supported (TRUE);
2337                 mono_set_partial_sharing_supported (TRUE);
2338         }
2339 }
2340
2341 /**
2342  * mono_jit_set_trace_options:
2343  * @options: string representing the trace options
2344  *
2345  * Set the options of the tracing engine. This function can be called before initializing
2346  * the mono runtime. See the --trace mono(1) manpage for the options format.
2347  *
2348  * Returns: #TRUE if the options where parsed and set correctly, #FALSE otherwise.
2349  */
2350 gboolean
2351 mono_jit_set_trace_options (const char* options)
2352 {
2353         MonoTraceSpec *trace_opt = mono_trace_parse_options (options);
2354         if (trace_opt == NULL)
2355                 return FALSE;
2356         mono_jit_trace_calls = trace_opt;
2357         return TRUE;
2358 }
2359
2360 /**
2361  * mono_set_signal_chaining:
2362  *
2363  *   Enable/disable signal chaining. This should be called before mono_jit_init ().
2364  * If signal chaining is enabled, the runtime saves the original signal handlers before
2365  * installing its own handlers, and calls the original ones in the following cases:
2366  * - a SIGSEGV/SIGABRT signal received while executing native (i.e. not JITted) code.
2367  * - SIGPROF
2368  * - SIGFPE
2369  * - SIGQUIT
2370  * - SIGUSR2
2371  * Signal chaining only works on POSIX platforms.
2372  */
2373 void
2374 mono_set_signal_chaining (gboolean chain_signals)
2375 {
2376         mono_do_signal_chaining = chain_signals;
2377 }
2378
2379 /**
2380  * mono_set_crash_chaining:
2381  *
2382  * Enable/disable crash chaining due to signals. When a fatal signal is delivered and
2383  * Mono doesn't know how to handle it, it will invoke the crash handler. If chrash chaining
2384  * is enabled, it will first print its crash information and then try to chain with the native handler.
2385  */
2386 void
2387 mono_set_crash_chaining (gboolean chain_crashes)
2388 {
2389         mono_do_crash_chaining = chain_crashes;
2390 }
2391
2392 /**
2393  * mono_parse_options_from:
2394  * @options: string containing strings 
2395  * @ref_argc: pointer to the argc variable that might be updated 
2396  * @ref_argv: pointer to the argv string vector variable that might be updated
2397  *
2398  * This function parses the contents of the `MONO_ENV_OPTIONS`
2399  * environment variable as if they were parsed by a command shell
2400  * splitting the contents by spaces into different elements of the
2401  * @argv vector.  This method supports quoting with both the " and '
2402  * characters.  Inside quoting, spaces and tabs are significant,
2403  * otherwise, they are considered argument separators.
2404  *
2405  * The \ character can be used to escape the next character which will
2406  * be added to the current element verbatim.  Typically this is used
2407  * inside quotes.   If the quotes are not balanced, this method 
2408  *
2409  * If the environment variable is empty, no changes are made
2410  * to the values pointed by @ref_argc and @ref_argv.
2411  *
2412  * Otherwise the @ref_argv is modified to point to a new array that contains
2413  * all the previous elements contained in the vector, plus the values parsed.
2414  * The @argc is updated to match the new number of parameters.
2415  *
2416  * Returns: The value NULL is returned on success, otherwise a g_strdup allocated
2417  * string is returned (this is an alias to malloc under normal circumstances) that
2418  * contains the error message that happened during parsing.
2419  */
2420 char *
2421 mono_parse_options_from (const char *options, int *ref_argc, char **ref_argv [])
2422 {
2423         int argc = *ref_argc;
2424         char **argv = *ref_argv;
2425         GPtrArray *array = g_ptr_array_new ();
2426         GString *buffer = g_string_new ("");
2427         const char *p;
2428         unsigned i;
2429         gboolean in_quotes = FALSE;
2430         char quote_char = '\0';
2431
2432         if (options == NULL)
2433                 return NULL;
2434         
2435         for (p = options; *p; p++){
2436                 switch (*p){
2437                 case ' ': case '\t':
2438                         if (!in_quotes) {
2439                                 if (buffer->len != 0){
2440                                         g_ptr_array_add (array, g_strdup (buffer->str));
2441                                         g_string_truncate (buffer, 0);
2442                                 }
2443                         } else {
2444                                 g_string_append_c (buffer, *p);
2445                         }
2446                         break;
2447                 case '\\':
2448                         if (p [1]){
2449                                 g_string_append_c (buffer, p [1]);
2450                                 p++;
2451                         }
2452                         break;
2453                 case '\'':
2454                 case '"':
2455                         if (in_quotes) {
2456                                 if (quote_char == *p)
2457                                         in_quotes = FALSE;
2458                                 else
2459                                         g_string_append_c (buffer, *p);
2460                         } else {
2461                                 in_quotes = TRUE;
2462                                 quote_char = *p;
2463                         }
2464                         break;
2465                 default:
2466                         g_string_append_c (buffer, *p);
2467                         break;
2468                 }
2469         }
2470         if (in_quotes) 
2471                 return g_strdup_printf ("Unmatched quotes in value: [%s]\n", options);
2472                 
2473         if (buffer->len != 0)
2474                 g_ptr_array_add (array, g_strdup (buffer->str));
2475         g_string_free (buffer, TRUE);
2476
2477         if (array->len > 0){
2478                 int new_argc = array->len + argc;
2479                 char **new_argv = g_new (char *, new_argc + 1);
2480                 int j;
2481
2482                 new_argv [0] = argv [0];
2483                 
2484                 /* First the environment variable settings, to allow the command line options to override */
2485                 for (i = 0; i < array->len; i++)
2486                         new_argv [i+1] = (char *)g_ptr_array_index (array, i);
2487                 i++;
2488                 for (j = 1; j < argc; j++)
2489                         new_argv [i++] = argv [j];
2490                 new_argv [i] = NULL;
2491
2492                 *ref_argc = new_argc;
2493                 *ref_argv = new_argv;
2494         }
2495         g_ptr_array_free (array, TRUE);
2496         return NULL;
2497 }
2498
2499 /**
2500  * mono_parse_env_options:
2501  * @ref_argc: pointer to the argc variable that might be updated 
2502  * @ref_argv: pointer to the argv string vector variable that might be updated
2503  *
2504  * This function parses the contents of the `MONO_ENV_OPTIONS`
2505  * environment variable as if they were parsed by a command shell
2506  * splitting the contents by spaces into different elements of the
2507  * @argv vector.  This method supports quoting with both the " and '
2508  * characters.  Inside quoting, spaces and tabs are significant,
2509  * otherwise, they are considered argument separators.
2510  *
2511  * The \ character can be used to escape the next character which will
2512  * be added to the current element verbatim.  Typically this is used
2513  * inside quotes.   If the quotes are not balanced, this method 
2514  *
2515  * If the environment variable is empty, no changes are made
2516  * to the values pointed by @ref_argc and @ref_argv.
2517  *
2518  * Otherwise the @ref_argv is modified to point to a new array that contains
2519  * all the previous elements contained in the vector, plus the values parsed.
2520  * The @argc is updated to match the new number of parameters.
2521  *
2522  * If there is an error parsing, this method will terminate the process by
2523  * calling exit(1).
2524  *
2525  * An alternative to this method that allows an arbitrary string to be parsed
2526  * and does not exit on error is the `api:mono_parse_options_from`.
2527  */
2528 void
2529 mono_parse_env_options (int *ref_argc, char **ref_argv [])
2530 {
2531         char *ret;
2532         
2533         const char *env_options = g_getenv ("MONO_ENV_OPTIONS");
2534         if (env_options == NULL)
2535                 return;
2536         ret = mono_parse_options_from (env_options, ref_argc, ref_argv);
2537         if (ret == NULL)
2538                 return;
2539         fprintf (stderr, "%s", ret);
2540         exit (1);
2541 }
2542