RtsFlags: Clean up stale CPP
[ghc.git] / rts / RtsFlags.c
1 /* -----------------------------------------------------------------------------
2 *
3 * (c) The AQUA Project, Glasgow University, 1994-1997
4 * (c) The GHC Team, 1998-2006
5 *
6 * Functions for parsing the argument list.
7 *
8 * ---------------------------------------------------------------------------*/
9
10 #include "PosixSource.h"
11 #include "Rts.h"
12
13 #include "RtsUtils.h"
14 #include "Profiling.h"
15 #include "RtsFlags.h"
16 #include "sm/OSMem.h"
17 #include "hooks/Hooks.h"
18
19 #ifdef HAVE_CTYPE_H
20 #include <ctype.h>
21 #endif
22
23 #include <string.h>
24
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28
29 #ifdef HAVE_SYS_TYPES_H
30 #include <sys/types.h>
31 #endif
32
33 // Flag Structure
34 RTS_FLAGS RtsFlags;
35
36 /*
37 * Split argument lists
38 */
39 int prog_argc = 0; /* an "int" so as to match normal "argc" */
40 char **prog_argv = NULL;
41 int full_prog_argc = 0; /* an "int" so as to match normal "argc" */
42 char **full_prog_argv = NULL;
43 char *prog_name = NULL; /* 'basename' of prog_argv[0] */
44 int rts_argc = 0; /* ditto */
45 char **rts_argv = NULL;
46 int rts_argv_size = 0;
47 #if defined(mingw32_HOST_OS)
48 // On Windows, we want to use GetCommandLineW rather than argc/argv,
49 // but we need to mutate the command line arguments for withProgName and
50 // friends. The System.Environment module achieves that using this bit of
51 // shared state:
52 int win32_prog_argc = 0;
53 wchar_t **win32_prog_argv = NULL;
54 #endif
55
56 // The global rtsConfig, set from the RtsConfig supplied by the call
57 // to hs_init_ghc().
58 RtsConfig rtsConfig;
59
60 const RtsConfig defaultRtsConfig = {
61 .rts_opts_enabled = RtsOptsSafeOnly,
62 .rts_opts_suggestions = rtsTrue,
63 .rts_opts = NULL,
64 .rts_hs_main = rtsFalse,
65 .keep_cafs = rtsFalse,
66 .defaultsHook = FlagDefaultsHook,
67 .onExitHook = OnExitHook,
68 .stackOverflowHook = StackOverflowHook,
69 .outOfHeapHook = OutOfHeapHook,
70 .mallocFailHook = MallocFailHook,
71 .gcDoneHook = NULL
72 };
73
74 /*
75 * constants, used later
76 */
77 #define RTS 1
78 #define PGM 0
79
80 /* -----------------------------------------------------------------------------
81 Static function decls
82 -------------------------------------------------------------------------- */
83
84 static void procRtsOpts (int rts_argc0, RtsOptsEnabledEnum enabled);
85
86 static void normaliseRtsOpts (void);
87
88 static void initStatsFile (FILE *f);
89
90 static int openStatsFile (
91 char *filename, const char *FILENAME_FMT, FILE **file_ret);
92
93 static StgWord64 decodeSize (
94 const char *flag, nat offset, StgWord64 min, StgWord64 max);
95
96 static void bad_option (const char *s);
97
98 #ifdef TRACING
99 static void read_trace_flags(char *arg);
100 #endif
101
102 static void errorUsage (void) GNU_ATTRIBUTE(__noreturn__);
103
104 static char * copyArg (char *arg);
105 static char ** copyArgv (int argc, char *argv[]);
106 static void freeArgv (int argc, char *argv[]);
107
108 static void errorRtsOptsDisabled (const char *s);
109
110 /* -----------------------------------------------------------------------------
111 * Command-line option parsing routines.
112 * ---------------------------------------------------------------------------*/
113
114 void initRtsFlagsDefaults(void)
115 {
116 StgWord64 maxStkSize = 8 * getPhysicalMemorySize() / 10;
117 // if getPhysicalMemorySize fails just move along with an 8MB limit
118 if (maxStkSize == 0)
119 maxStkSize = 8 * 1024 * 1024;
120
121 RtsFlags.GcFlags.statsFile = NULL;
122 RtsFlags.GcFlags.giveStats = NO_GC_STATS;
123
124 RtsFlags.GcFlags.maxStkSize = maxStkSize / sizeof(W_);
125 RtsFlags.GcFlags.initialStkSize = 1024 / sizeof(W_);
126 RtsFlags.GcFlags.stkChunkSize = (32 * 1024) / sizeof(W_);
127 RtsFlags.GcFlags.stkChunkBufferSize = (1 * 1024) / sizeof(W_);
128
129 RtsFlags.GcFlags.minAllocAreaSize = (512 * 1024) / BLOCK_SIZE;
130 RtsFlags.GcFlags.nurseryChunkSize = 0;
131 RtsFlags.GcFlags.minOldGenSize = (1024 * 1024) / BLOCK_SIZE;
132 RtsFlags.GcFlags.maxHeapSize = 0; /* off by default */
133 RtsFlags.GcFlags.heapSizeSuggestion = 0; /* none */
134 RtsFlags.GcFlags.heapSizeSuggestionAuto = rtsFalse;
135 RtsFlags.GcFlags.pcFreeHeap = 3; /* 3% */
136 RtsFlags.GcFlags.oldGenFactor = 2;
137 RtsFlags.GcFlags.generations = 2;
138 RtsFlags.GcFlags.squeezeUpdFrames = rtsTrue;
139 RtsFlags.GcFlags.compact = rtsFalse;
140 RtsFlags.GcFlags.compactThreshold = 30.0;
141 RtsFlags.GcFlags.sweep = rtsFalse;
142 RtsFlags.GcFlags.idleGCDelayTime = USToTime(300000); // 300ms
143 #ifdef THREADED_RTS
144 RtsFlags.GcFlags.doIdleGC = rtsTrue;
145 #else
146 RtsFlags.GcFlags.doIdleGC = rtsFalse;
147 #endif
148
149 #if osf3_HOST_OS
150 /* ToDo: Perhaps by adjusting this value we can make linking without
151 * -static work (i.e., not generate a core-dumping executable)? */
152 # if SIZEOF_VOID_P == 8
153 RtsFlags.GcFlags.heapBase = 0x180000000L;
154 # else
155 # error I have no idea where to begin the heap on a non-64-bit osf3 machine.
156 # endif
157 #else
158 RtsFlags.GcFlags.heapBase = 0; /* means don't care */
159 #endif
160 RtsFlags.GcFlags.allocLimitGrace = (100*1024) / BLOCK_SIZE;
161
162 #ifdef DEBUG
163 RtsFlags.DebugFlags.scheduler = rtsFalse;
164 RtsFlags.DebugFlags.interpreter = rtsFalse;
165 RtsFlags.DebugFlags.weak = rtsFalse;
166 RtsFlags.DebugFlags.gccafs = rtsFalse;
167 RtsFlags.DebugFlags.gc = rtsFalse;
168 RtsFlags.DebugFlags.block_alloc = rtsFalse;
169 RtsFlags.DebugFlags.sanity = rtsFalse;
170 RtsFlags.DebugFlags.stable = rtsFalse;
171 RtsFlags.DebugFlags.stm = rtsFalse;
172 RtsFlags.DebugFlags.prof = rtsFalse;
173 RtsFlags.DebugFlags.apply = rtsFalse;
174 RtsFlags.DebugFlags.linker = rtsFalse;
175 RtsFlags.DebugFlags.squeeze = rtsFalse;
176 RtsFlags.DebugFlags.hpc = rtsFalse;
177 RtsFlags.DebugFlags.sparks = rtsFalse;
178 #endif
179
180 #if defined(PROFILING)
181 RtsFlags.CcFlags.doCostCentres = 0;
182 #endif /* PROFILING */
183
184 RtsFlags.ProfFlags.doHeapProfile = rtsFalse;
185 RtsFlags.ProfFlags. heapProfileInterval = USToTime(100000); // 100ms
186
187 #ifdef PROFILING
188 RtsFlags.ProfFlags.includeTSOs = rtsFalse;
189 RtsFlags.ProfFlags.showCCSOnException = rtsFalse;
190 RtsFlags.ProfFlags.maxRetainerSetSize = 8;
191 RtsFlags.ProfFlags.ccsLength = 25;
192 RtsFlags.ProfFlags.modSelector = NULL;
193 RtsFlags.ProfFlags.descrSelector = NULL;
194 RtsFlags.ProfFlags.typeSelector = NULL;
195 RtsFlags.ProfFlags.ccSelector = NULL;
196 RtsFlags.ProfFlags.ccsSelector = NULL;
197 RtsFlags.ProfFlags.retainerSelector = NULL;
198 RtsFlags.ProfFlags.bioSelector = NULL;
199 #endif
200
201 #ifdef TRACING
202 RtsFlags.TraceFlags.tracing = TRACE_NONE;
203 RtsFlags.TraceFlags.timestamp = rtsFalse;
204 RtsFlags.TraceFlags.scheduler = rtsFalse;
205 RtsFlags.TraceFlags.gc = rtsFalse;
206 RtsFlags.TraceFlags.sparks_sampled= rtsFalse;
207 RtsFlags.TraceFlags.sparks_full = rtsFalse;
208 RtsFlags.TraceFlags.user = rtsFalse;
209 #endif
210
211 #ifdef PROFILING
212 // When profiling we want a lot more ticks
213 RtsFlags.MiscFlags.tickInterval = USToTime(1000); // 1ms
214 #else
215 RtsFlags.MiscFlags.tickInterval = DEFAULT_TICK_INTERVAL;
216 #endif
217 RtsFlags.ConcFlags.ctxtSwitchTime = USToTime(20000); // 20ms
218
219 RtsFlags.MiscFlags.install_signal_handlers = rtsTrue;
220 RtsFlags.MiscFlags.machineReadable = rtsFalse;
221 RtsFlags.MiscFlags.linkerMemBase = 0;
222
223 #ifdef THREADED_RTS
224 RtsFlags.ParFlags.nNodes = 1;
225 RtsFlags.ParFlags.migrate = rtsTrue;
226 RtsFlags.ParFlags.parGcEnabled = 1;
227 RtsFlags.ParFlags.parGcGen = 0;
228 RtsFlags.ParFlags.parGcLoadBalancingEnabled = rtsTrue;
229 RtsFlags.ParFlags.parGcLoadBalancingGen = 1;
230 RtsFlags.ParFlags.parGcNoSyncWithIdle = 0;
231 RtsFlags.ParFlags.setAffinity = 0;
232 #endif
233
234 #if defined(THREADED_RTS)
235 RtsFlags.ParFlags.maxLocalSparks = 4096;
236 #endif /* THREADED_RTS */
237
238 #ifdef TICKY_TICKY
239 RtsFlags.TickyFlags.showTickyStats = rtsFalse;
240 RtsFlags.TickyFlags.tickyFile = NULL;
241 #endif
242
243 #ifdef USE_PAPI
244 /* By default no special measurements taken */
245 RtsFlags.PapiFlags.eventType = 0;
246 RtsFlags.PapiFlags.numUserEvents = 0;
247 #endif
248 }
249
250 static const char *
251 usage_text[] = {
252 "",
253 "Usage: <prog> <args> [+RTS <rtsopts> | -RTS <args>] ... --RTS <args>",
254 "",
255 " +RTS Indicates run time system options follow",
256 " -RTS Indicates program arguments follow",
257 " --RTS Indicates that ALL subsequent arguments will be given to the",
258 " program (including any of these RTS flags)",
259 "",
260 "The following run time system options are available:",
261 "",
262 " -? Prints this message and exits; the program is not executed",
263 " --info Print information about the RTS used by this program",
264 "",
265 " -K<size> Sets the maximum stack size (default: 80% of the heap)",
266 " Egs: -K32k -K512k -K8M",
267 " -ki<size> Sets the initial thread stack size (default 1k) Egs: -ki4k -ki2m",
268 " -kc<size> Sets the stack chunk size (default 32k)",
269 " -kb<size> Sets the stack chunk buffer size (default 1k)",
270 "",
271 " -A<size> Sets the minimum allocation area size (default 512k) Egs: -A1m -A10k",
272 " -n<size> Allocation area chunk size (0 = disabled, default: 0)",
273 " -O<size> Sets the minimum size of the old generation (default 1M)",
274 " -M<size> Sets the maximum heap size (default unlimited) Egs: -M256k -M1G",
275 " -H<size> Sets the minimum heap size (default 0M) Egs: -H24m -H1G",
276 " -m<n> Minimum % of heap which must be available (default 3%)",
277 " -G<n> Number of generations (default: 2)",
278 " -c<n> Use in-place compaction instead of copying in the oldest generation",
279 " when live data is at least <n>% of the maximum heap size set with",
280 " -M (default: 30%)",
281 " -c Use in-place compaction for all oldest generation collections",
282 " (the default is to use copying)",
283 " -w Use mark-region for the oldest generation (experimental)",
284 #if defined(THREADED_RTS)
285 " -I<sec> Perform full GC after <sec> idle time (default: 0.3, 0 == off)",
286 #endif
287 "",
288 " -T Collect GC statistics (useful for in-program statistics access)",
289 " -t[<file>] One-line GC statistics (if <file> omitted, uses stderr)",
290 " -s[<file>] Summary GC statistics (if <file> omitted, uses stderr)",
291 " -S[<file>] Detailed GC statistics (if <file> omitted, uses stderr)",
292 "",
293 "",
294 " -Z Don't squeeze out update frames on stack overflow",
295 " -B Sound the bell at the start of each garbage collection",
296 #if defined(PROFILING)
297 "",
298 " -p Time/allocation profile (output file <program>.prof)",
299 " -P More detailed Time/Allocation profile",
300 " -Pa Give information about *all* cost centres",
301 "",
302 " -h<break-down> Heap residency profile (hp2ps) (output file <program>.hp)",
303 " break-down: c = cost centre stack (default)",
304 " m = module",
305 " d = closure description",
306 " y = type description",
307 " r = retainer",
308 " b = biography (LAG,DRAG,VOID,USE)",
309 " A subset of closures may be selected thusly:",
310 " -hc<cc>,... specific cost centre(s) (top of stack only)",
311 " -hC<cc>,... specific cost centre(s) (anywhere in stack)",
312 " -hm<mod>... all cost centres from the specified modules(s)",
313 " -hd<des>,... closures with specified closure descriptions",
314 " -hy<typ>... closures with specified type descriptions",
315 " -hr<cc>... closures with specified retainers",
316 " -hb<bio>... closures with specified biographies (lag,drag,void,use)",
317 "",
318 " -R<size> Set the maximum retainer set size (default: 8)",
319 "",
320 " -L<chars> Maximum length of a cost-centre stack in a heap profile",
321 " (default: 25)",
322 "",
323 " -xt Include threads (TSOs) in a heap profile",
324 "",
325 " -xc Show current cost centre stack on raising an exception",
326 #endif /* PROFILING */
327
328 #ifdef TRACING
329 "",
330 " -l[flags] Log events in binary format to the file <program>.eventlog",
331 # ifdef DEBUG
332 " -v[flags] Log events to stderr",
333 # endif
334 " where [flags] can contain:",
335 " s scheduler events",
336 " g GC and heap events",
337 " p par spark events (sampled)",
338 " f par spark events (full detail)",
339 " u user events (emitted from Haskell code)",
340 " a all event classes above",
341 # ifdef DEBUG
342 " t add time stamps (only useful with -v)",
343 # endif
344 " -x disable an event class, for any flag above",
345 " the initial enabled event classes are 'sgpu'",
346 #endif
347
348 #if !defined(PROFILING)
349 "",
350 " -h Heap residency profile (output file <program>.hp)",
351 #endif
352 " -i<sec> Time between heap profile samples (seconds, default: 0.1)",
353 "",
354 #if defined(TICKY_TICKY)
355 " -r<file> Produce ticky-ticky statistics (with -rstderr for stderr)",
356 "",
357 #endif
358 " -C<secs> Context-switch interval in seconds.",
359 " 0 or no argument means switch as often as possible.",
360 " Default: 0.02 sec.",
361 " -V<secs> Master tick interval in seconds (0 == disable timer).",
362 " This sets the resolution for -C and the heap profile timer -i,",
363 " and is the frequence of time profile samples.",
364 #ifdef PROFILING
365 " Default: 0.001 sec.",
366 #else
367 " Default: 0.01 sec.",
368 #endif
369 "",
370 #if defined(DEBUG)
371 " -Ds DEBUG: scheduler",
372 " -Di DEBUG: interpreter",
373 " -Dw DEBUG: weak",
374 " -DG DEBUG: gccafs",
375 " -Dg DEBUG: gc",
376 " -Db DEBUG: block",
377 " -DS DEBUG: sanity",
378 " -Dt DEBUG: stable",
379 " -Dp DEBUG: prof",
380 " -Da DEBUG: apply",
381 " -Dl DEBUG: linker",
382 " -Dm DEBUG: stm",
383 " -Dz DEBUG: stack squeezing",
384 " -Dc DEBUG: program coverage",
385 " -Dr DEBUG: sparks",
386 "",
387 " NOTE: DEBUG events are sent to stderr by default; add -l to create a",
388 " binary event log file instead.",
389 "",
390 #endif /* DEBUG */
391 #if defined(THREADED_RTS) && !defined(NOSMP)
392 " -N[<n>] Use <n> processors (default: 1, -N alone determines",
393 " the number of processors to use automatically)",
394 " -qg[<n>] Use parallel GC only for generations >= <n>",
395 " (default: 0, -qg alone turns off parallel GC)",
396 " -qb[<n>] Use load-balancing in the parallel GC only for generations >= <n>",
397 " (default: 1, -qb alone turns off load-balancing)",
398 " -qa Use the OS to set thread affinity (experimental)",
399 " -qm Don't automatically migrate threads between CPUs",
400 " -qi<n> If a processor has been idle for the last <n> GCs, do not",
401 " wake it up for a non-load-balancing parallel GC.",
402 " (0 disables, default: 0)",
403 #endif
404 " --install-signal-handlers=<yes|no>",
405 " Install signal handlers (default: yes)",
406 #if defined(THREADED_RTS)
407 " -e<n> Maximum number of outstanding local sparks (default: 4096)",
408 #endif
409 #if defined(x86_64_HOST_ARCH)
410 " -xm Base address to mmap memory in the GHCi linker",
411 " (hex; must be <80000000)",
412 #endif
413 #if defined(USE_PAPI)
414 " -aX CPU performance counter measurements using PAPI",
415 " (use with the -s<file> option). X is one of:",
416 "",
417 /* " y - cycles", */
418 " 1 - level 1 cache misses",
419 " 2 - level 2 cache misses",
420 " b - branch mispredictions",
421 " s - stalled cycles",
422 " e - cache miss and branch misprediction events",
423 " +PAPI_EVENT - collect papi preset event PAPI_EVENT",
424 " #NATIVE_EVENT - collect native event NATIVE_EVENT (in hex)",
425 #endif
426 " -xq The allocation limit given to a thread after it receives",
427 " an AllocationLimitExceeded exception. (default: 100k)",
428 "",
429 "RTS options may also be specified using the GHCRTS environment variable.",
430 "",
431 "Other RTS options may be available for programs compiled a different way.",
432 "The GHC User's Guide has full details.",
433 "",
434 0
435 };
436
437 STATIC_INLINE rtsBool strequal(const char *a, const char * b)
438 {
439 return(strcmp(a, b) == 0);
440 }
441
442 // We can't predict up front how much space we'll need for rts_argv,
443 // because it involves parsing ghc_rts_opts and GHCRTS, so we
444 // expand it on demand.
445 static void appendRtsArg (char *arg)
446 {
447 if (rts_argc == rts_argv_size) {
448 rts_argv_size *= 2;
449 rts_argv = stgReallocBytes(rts_argv, rts_argv_size * sizeof (char *),
450 "RtsFlags.c:appendRtsArg");
451 }
452 rts_argv[rts_argc++] = arg;
453 }
454
455 static void splitRtsFlags(const char *s)
456 {
457 const char *c1, *c2;
458 char *t;
459
460 c1 = s;
461 do {
462 while (isspace(*c1)) { c1++; };
463 c2 = c1;
464 while (!isspace(*c2) && *c2 != '\0') { c2++; };
465
466 if (c1 == c2) { break; }
467
468 t = stgMallocBytes(c2-c1+1, "RtsFlags.c:splitRtsFlags()");
469 strncpy(t, c1, c2-c1);
470 t[c2-c1] = '\0';
471 appendRtsArg(t);
472
473 c1 = c2;
474 } while (*c1 != '\0');
475 }
476
477 static void errorRtsOptsDisabled(const char *s)
478 {
479 char *advice;
480 if (rtsConfig.rts_hs_main) {
481 advice = "Link with -rtsopts to enable them.";
482 } else {
483 advice = "Use hs_init_with_rtsopts() to enable them.";
484 }
485 errorBelch(s, advice);
486 }
487
488 /* -----------------------------------------------------------------------------
489 Parse the command line arguments, collecting options for the RTS.
490
491 On return:
492 - argv[] is *modified*, any RTS options have been stripped out
493 - *argc contains the new count of arguments in argv[]
494
495 - rts_argv[] (global) contains a copy of the collected RTS args
496 - rts_argc (global) contains the count of args in rts_argv
497
498 - prog_argv[] (global) contains a copy of the non-RTS args (== argv)
499 - prog_argc (global) contains the count of args in prog_argv
500
501 - prog_name (global) contains the basename of prog_argv[0]
502
503 - rtsConfig (global) contains the supplied RtsConfig
504
505 -------------------------------------------------------------------------- */
506
507 void setupRtsFlags (int *argc, char *argv[], RtsConfig rts_config)
508 {
509 nat mode;
510 nat total_arg;
511 nat arg, rts_argc0;
512
513 rtsConfig = rts_config;
514
515 setProgName (argv);
516 total_arg = *argc;
517 arg = 1;
518
519 if (*argc > 1) { *argc = 1; };
520 rts_argc = 0;
521
522 rts_argv_size = total_arg + 1;
523 rts_argv = stgMallocBytes(rts_argv_size * sizeof (char *), "setupRtsFlags");
524
525 rts_argc0 = rts_argc;
526
527 // process arguments from the -with-rtsopts compile-time flag first
528 // (arguments from the GHCRTS environment variable and the command
529 // line override these).
530 {
531 if (rtsConfig.rts_opts != NULL) {
532 splitRtsFlags(rtsConfig.rts_opts);
533 // opts from rts_opts are always enabled:
534 procRtsOpts(rts_argc0, RtsOptsAll);
535 rts_argc0 = rts_argc;
536 }
537 }
538
539 // process arguments from the GHCRTS environment variable next
540 // (arguments from the command line override these).
541 {
542 char *ghc_rts = getenv("GHCRTS");
543
544 if (ghc_rts != NULL) {
545 if (rtsConfig.rts_opts_enabled == RtsOptsNone) {
546 errorRtsOptsDisabled(
547 "Warning: Ignoring GHCRTS variable as RTS options are disabled.\n %s");
548 // We don't actually exit, just warn
549 } else {
550 splitRtsFlags(ghc_rts);
551 procRtsOpts(rts_argc0, rtsConfig.rts_opts_enabled);
552 rts_argc0 = rts_argc;
553 }
554 }
555 }
556
557 // Split arguments (argv) into PGM (argv) and RTS (rts_argv) parts
558 // argv[0] must be PGM argument -- leave in argv
559
560 for (mode = PGM; arg < total_arg; arg++) {
561 // The '--RTS' argument disables all future +RTS ... -RTS processing.
562 if (strequal("--RTS", argv[arg])) {
563 arg++;
564 break;
565 }
566 // The '--' argument is passed through to the program, but
567 // disables all further +RTS ... -RTS processing.
568 else if (strequal("--", argv[arg])) {
569 break;
570 }
571 else if (strequal("+RTS", argv[arg])) {
572 mode = RTS;
573 }
574 else if (strequal("-RTS", argv[arg])) {
575 mode = PGM;
576 }
577 else if (mode == RTS) {
578 appendRtsArg(copyArg(argv[arg]));
579 }
580 else {
581 argv[(*argc)++] = argv[arg];
582 }
583 }
584 // process remaining program arguments
585 for (; arg < total_arg; arg++) {
586 argv[(*argc)++] = argv[arg];
587 }
588 argv[*argc] = (char *) 0;
589
590 procRtsOpts(rts_argc0, rtsConfig.rts_opts_enabled);
591
592 appendRtsArg((char *)0);
593 rts_argc--; // appendRtsArg will have bumped it for the NULL (#7227)
594
595 normaliseRtsOpts();
596
597 setProgArgv(*argc, argv);
598
599 if (RtsFlags.GcFlags.statsFile != NULL) {
600 initStatsFile (RtsFlags.GcFlags.statsFile);
601 }
602 if (RtsFlags.TickyFlags.tickyFile != NULL) {
603 initStatsFile (RtsFlags.GcFlags.statsFile);
604 }
605 }
606
607 /* -----------------------------------------------------------------------------
608 * procRtsOpts: Process rts_argv between rts_argc0 and rts_argc.
609 * -------------------------------------------------------------------------- */
610
611 #if defined(HAVE_UNISTD_H) && defined(HAVE_SYS_TYPES_H) && !defined(mingw32_HOST_OS)
612 static void checkSuid(RtsOptsEnabledEnum enabled)
613 {
614 if (enabled == RtsOptsSafeOnly) {
615 /* This doesn't cover linux/posix capabilities like CAP_DAC_OVERRIDE,
616 we'd have to link with -lcap for that. */
617 if ((getuid() != geteuid()) || (getgid() != getegid())) {
618 errorRtsOptsDisabled(
619 "RTS options are disabled for setuid binaries. %s");
620 stg_exit(EXIT_FAILURE);
621 }
622 }
623 }
624 #else
625 static void checkSuid (RtsOptsEnabledEnum enabled STG_UNUSED)
626 {
627 }
628 #endif
629
630 static void checkUnsafe(RtsOptsEnabledEnum enabled)
631 {
632 if (enabled == RtsOptsSafeOnly) {
633 errorRtsOptsDisabled("Most RTS options are disabled. %s");
634 stg_exit(EXIT_FAILURE);
635 }
636 }
637
638 static void procRtsOpts (int rts_argc0,
639 RtsOptsEnabledEnum rtsOptsEnabled)
640 {
641 rtsBool error = rtsFalse;
642 int arg;
643 int unchecked_arg_start;
644
645 if (!(rts_argc0 < rts_argc)) return;
646
647 if (rtsOptsEnabled == RtsOptsNone) {
648 errorRtsOptsDisabled("RTS options are disabled. %s");
649 stg_exit(EXIT_FAILURE);
650 }
651
652 checkSuid(rtsOptsEnabled);
653
654 // Process RTS (rts_argv) part: mainly to determine statsfile
655 for (arg = rts_argc0; arg < rts_argc; arg++) {
656
657 /* We handle RtsOptsSafeOnly mode by declaring each option as
658 either OPTION_SAFE or OPTION_UNSAFE. To make sure we cover
659 every branch we use an option_checked flag which is reset
660 at the start each iteration and checked at the end. */
661 rtsBool option_checked = rtsFalse;
662
663 #define OPTION_SAFE option_checked = rtsTrue;
664 #define OPTION_UNSAFE checkUnsafe(rtsOptsEnabled); option_checked = rtsTrue;
665
666 if (rts_argv[arg][0] != '-') {
667 fflush(stdout);
668 errorBelch("unexpected RTS argument: %s", rts_argv[arg]);
669 error = rtsTrue;
670
671 } else {
672 /* 0 is dash, 1 is first letter */
673 /* see Trac #9839 */
674 unchecked_arg_start = 1;
675 switch(rts_argv[arg][1]) {
676
677 /* process: general args, then PROFILING-only ones, then
678 CONCURRENT-only, TICKY-only (same order as defined in
679 RtsFlags.lh); within those groups, mostly in
680 case-insensitive alphabetical order. Final group is
681 x*, which allows for more options.
682 */
683
684 #ifdef TICKY_TICKY
685 # define TICKY_BUILD_ONLY(x) x
686 #else
687 # define TICKY_BUILD_ONLY(x) \
688 errorBelch("the flag %s requires the program to be built with -ticky", \
689 rts_argv[arg]); \
690 error = rtsTrue;
691 #endif
692
693 #ifdef PROFILING
694 # define PROFILING_BUILD_ONLY(x) x
695 #else
696 # define PROFILING_BUILD_ONLY(x) \
697 errorBelch("the flag %s requires the program to be built with -prof", \
698 rts_argv[arg]); \
699 error = rtsTrue;
700 #endif
701
702 #ifdef TRACING
703 # define TRACING_BUILD_ONLY(x) x
704 #else
705 # define TRACING_BUILD_ONLY(x) \
706 errorBelch("the flag %s requires the program to be built with -eventlog or -debug", \
707 rts_argv[arg]); \
708 error = rtsTrue;
709 #endif
710
711 #ifdef THREADED_RTS
712 # define THREADED_BUILD_ONLY(x) x
713 #else
714 # define THREADED_BUILD_ONLY(x) \
715 errorBelch("the flag %s requires the program to be built with -threaded", \
716 rts_argv[arg]); \
717 error = rtsTrue;
718 #endif
719
720 #ifdef DEBUG
721 # define DEBUG_BUILD_ONLY(x) x
722 #else
723 # define DEBUG_BUILD_ONLY(x) \
724 errorBelch("the flag %s requires the program to be built with -debug", \
725 rts_argv[arg]); \
726 error = rtsTrue;
727 #endif
728
729 /* =========== GENERAL ========================== */
730 case '?':
731 OPTION_SAFE;
732 error = rtsTrue;
733 break;
734
735 /* This isn't going to allow us to keep related options
736 together as we add more --* flags. We really need a
737 proper options parser. */
738 case '-':
739 if (strequal("install-signal-handlers=yes",
740 &rts_argv[arg][2])) {
741 OPTION_UNSAFE;
742 RtsFlags.MiscFlags.install_signal_handlers = rtsTrue;
743 }
744 else if (strequal("install-signal-handlers=no",
745 &rts_argv[arg][2])) {
746 OPTION_UNSAFE;
747 RtsFlags.MiscFlags.install_signal_handlers = rtsFalse;
748 }
749 else if (strequal("machine-readable",
750 &rts_argv[arg][2])) {
751 OPTION_UNSAFE;
752 RtsFlags.MiscFlags.machineReadable = rtsTrue;
753 }
754 else if (strequal("info",
755 &rts_argv[arg][2])) {
756 OPTION_SAFE;
757 printRtsInfo();
758 stg_exit(0);
759 }
760 else {
761 OPTION_SAFE;
762 errorBelch("unknown RTS option: %s",rts_argv[arg]);
763 error = rtsTrue;
764 }
765 break;
766 case 'A':
767 OPTION_UNSAFE;
768 // minimum two blocks in the nursery, so that we have one to
769 // grab for allocate().
770 RtsFlags.GcFlags.minAllocAreaSize
771 = decodeSize(rts_argv[arg], 2, 2*BLOCK_SIZE, HS_INT_MAX)
772 / BLOCK_SIZE;
773 break;
774 case 'n':
775 OPTION_UNSAFE;
776 RtsFlags.GcFlags.nurseryChunkSize
777 = decodeSize(rts_argv[arg], 2, 2*BLOCK_SIZE, HS_INT_MAX)
778 / BLOCK_SIZE;
779 break;
780
781 #ifdef USE_PAPI
782 case 'a':
783 OPTION_UNSAFE;
784 switch(rts_argv[arg][2]) {
785 case '1':
786 RtsFlags.PapiFlags.eventType = PAPI_FLAG_CACHE_L1;
787 break;
788 case '2':
789 RtsFlags.PapiFlags.eventType = PAPI_FLAG_CACHE_L2;
790 break;
791 case 'b':
792 RtsFlags.PapiFlags.eventType = PAPI_FLAG_BRANCH;
793 break;
794 case 's':
795 RtsFlags.PapiFlags.eventType = PAPI_FLAG_STALLS;
796 break;
797 case 'e':
798 RtsFlags.PapiFlags.eventType = PAPI_FLAG_CB_EVENTS;
799 break;
800 case '+':
801 case '#':
802 if (RtsFlags.PapiFlags.numUserEvents >= MAX_PAPI_USER_EVENTS) {
803 errorBelch("maximum number of PAPI events reached");
804 stg_exit(EXIT_FAILURE);
805 }
806 nat eventNum = RtsFlags.PapiFlags.numUserEvents++;
807 char kind = rts_argv[arg][2];
808 nat eventKind = kind == '+' ? PAPI_PRESET_EVENT_KIND : PAPI_NATIVE_EVENT_KIND;
809
810 RtsFlags.PapiFlags.userEvents[eventNum] = rts_argv[arg] + 3;
811 RtsFlags.PapiFlags.eventType = PAPI_USER_EVENTS;
812 RtsFlags.PapiFlags.userEventsKind[eventNum] = eventKind;
813 break;
814 default:
815 bad_option( rts_argv[arg] );
816 }
817 break;
818 #endif
819
820 case 'B':
821 OPTION_UNSAFE;
822 RtsFlags.GcFlags.ringBell = rtsTrue;
823 unchecked_arg_start++;
824 goto check_rest;
825
826 case 'c':
827 OPTION_UNSAFE;
828 if (rts_argv[arg][2] != '\0') {
829 RtsFlags.GcFlags.compactThreshold =
830 atof(rts_argv[arg]+2);
831 } else {
832 RtsFlags.GcFlags.compact = rtsTrue;
833 }
834 break;
835
836 case 'w':
837 OPTION_UNSAFE;
838 RtsFlags.GcFlags.sweep = rtsTrue;
839 unchecked_arg_start++;
840 goto check_rest;
841
842 case 'F':
843 OPTION_UNSAFE;
844 RtsFlags.GcFlags.oldGenFactor = atof(rts_argv[arg]+2);
845
846 if (RtsFlags.GcFlags.oldGenFactor < 0)
847 bad_option( rts_argv[arg] );
848 break;
849
850 case 'D':
851 OPTION_SAFE;
852 DEBUG_BUILD_ONLY(
853 {
854 char *c;
855
856 for (c = rts_argv[arg] + 2; *c != '\0'; c++) {
857 switch (*c) {
858 case 's':
859 RtsFlags.DebugFlags.scheduler = rtsTrue;
860 break;
861 case 'i':
862 RtsFlags.DebugFlags.interpreter = rtsTrue;
863 break;
864 case 'w':
865 RtsFlags.DebugFlags.weak = rtsTrue;
866 break;
867 case 'G':
868 RtsFlags.DebugFlags.gccafs = rtsTrue;
869 break;
870 case 'g':
871 RtsFlags.DebugFlags.gc = rtsTrue;
872 break;
873 case 'b':
874 RtsFlags.DebugFlags.block_alloc = rtsTrue;
875 break;
876 case 'S':
877 RtsFlags.DebugFlags.sanity = rtsTrue;
878 break;
879 case 't':
880 RtsFlags.DebugFlags.stable = rtsTrue;
881 break;
882 case 'p':
883 RtsFlags.DebugFlags.prof = rtsTrue;
884 break;
885 case 'l':
886 RtsFlags.DebugFlags.linker = rtsTrue;
887 break;
888 case 'a':
889 RtsFlags.DebugFlags.apply = rtsTrue;
890 break;
891 case 'm':
892 RtsFlags.DebugFlags.stm = rtsTrue;
893 break;
894 case 'z':
895 RtsFlags.DebugFlags.squeeze = rtsTrue;
896 break;
897 case 'c':
898 RtsFlags.DebugFlags.hpc = rtsTrue;
899 break;
900 case 'r':
901 RtsFlags.DebugFlags.sparks = rtsTrue;
902 break;
903 default:
904 bad_option( rts_argv[arg] );
905 }
906 }
907 // -Dx also turns on -v. Use -l to direct trace
908 // events to the .eventlog file instead.
909 RtsFlags.TraceFlags.tracing = TRACE_STDERR;
910 })
911 break;
912
913 case 'K':
914 OPTION_UNSAFE;
915 RtsFlags.GcFlags.maxStkSize =
916 decodeSize(rts_argv[arg], 2, sizeof(W_), HS_WORD_MAX)
917 / sizeof(W_);
918 break;
919
920 case 'k':
921 OPTION_UNSAFE;
922 switch(rts_argv[arg][2]) {
923 case 'c':
924 RtsFlags.GcFlags.stkChunkSize =
925 decodeSize(rts_argv[arg], 3, sizeof(W_), HS_WORD_MAX)
926 / sizeof(W_);
927 break;
928 case 'b':
929 RtsFlags.GcFlags.stkChunkBufferSize =
930 decodeSize(rts_argv[arg], 3, sizeof(W_), HS_WORD_MAX)
931 / sizeof(W_);
932 break;
933 case 'i':
934 RtsFlags.GcFlags.initialStkSize =
935 decodeSize(rts_argv[arg], 3, sizeof(W_), HS_WORD_MAX)
936 / sizeof(W_);
937 break;
938 default:
939 RtsFlags.GcFlags.initialStkSize =
940 decodeSize(rts_argv[arg], 2, sizeof(W_), HS_WORD_MAX)
941 / sizeof(W_);
942 break;
943 }
944 break;
945
946 case 'M':
947 OPTION_UNSAFE;
948 RtsFlags.GcFlags.maxHeapSize =
949 decodeSize(rts_argv[arg], 2, BLOCK_SIZE, HS_WORD_MAX)
950 / BLOCK_SIZE;
951 /* user give size in *bytes* but "maxHeapSize" is in
952 * *blocks* */
953 break;
954
955 case 'm':
956 OPTION_UNSAFE;
957 RtsFlags.GcFlags.pcFreeHeap = atof(rts_argv[arg]+2);
958
959 if (RtsFlags.GcFlags.pcFreeHeap < 0 ||
960 RtsFlags.GcFlags.pcFreeHeap > 100)
961 bad_option( rts_argv[arg] );
962 break;
963
964 case 'G':
965 OPTION_UNSAFE;
966 RtsFlags.GcFlags.generations =
967 decodeSize(rts_argv[arg], 2, 1, HS_INT_MAX);
968 break;
969
970 case 'H':
971 OPTION_UNSAFE;
972 if (rts_argv[arg][2] == '\0') {
973 RtsFlags.GcFlags.heapSizeSuggestionAuto = rtsTrue;
974 } else {
975 RtsFlags.GcFlags.heapSizeSuggestion =
976 (nat)(decodeSize(rts_argv[arg], 2, BLOCK_SIZE, HS_WORD_MAX) / BLOCK_SIZE);
977 }
978 break;
979
980 case 'O':
981 OPTION_UNSAFE;
982 RtsFlags.GcFlags.minOldGenSize =
983 (nat)(decodeSize(rts_argv[arg], 2, BLOCK_SIZE,
984 HS_WORD_MAX)
985 / BLOCK_SIZE);
986 break;
987
988 case 'I': /* idle GC delay */
989 OPTION_UNSAFE;
990 if (rts_argv[arg][2] == '\0') {
991 /* use default */
992 } else {
993 Time t = fsecondsToTime(atof(rts_argv[arg]+2));
994 if (t == 0) {
995 RtsFlags.GcFlags.doIdleGC = rtsFalse;
996 } else {
997 RtsFlags.GcFlags.doIdleGC = rtsTrue;
998 RtsFlags.GcFlags.idleGCDelayTime = t;
999 }
1000 }
1001 break;
1002
1003 case 'T':
1004 OPTION_SAFE;
1005 RtsFlags.GcFlags.giveStats = COLLECT_GC_STATS;
1006 unchecked_arg_start++;
1007 goto check_rest; /* Don't initialize statistics file. */
1008
1009 case 'S':
1010 OPTION_SAFE; /* but see below */
1011 RtsFlags.GcFlags.giveStats = VERBOSE_GC_STATS;
1012 goto stats;
1013
1014 case 's':
1015 OPTION_SAFE; /* but see below */
1016 RtsFlags.GcFlags.giveStats = SUMMARY_GC_STATS;
1017 goto stats;
1018
1019 case 't':
1020 OPTION_SAFE; /* but see below */
1021 RtsFlags.GcFlags.giveStats = ONELINE_GC_STATS;
1022 goto stats;
1023
1024 stats:
1025 {
1026 int r;
1027 if (rts_argv[arg][2] != '\0') {
1028 OPTION_UNSAFE;
1029 }
1030 r = openStatsFile(rts_argv[arg]+2, NULL,
1031 &RtsFlags.GcFlags.statsFile);
1032 if (r == -1) { error = rtsTrue; }
1033 }
1034 break;
1035
1036 case 'Z':
1037 OPTION_UNSAFE;
1038 RtsFlags.GcFlags.squeezeUpdFrames = rtsFalse;
1039 unchecked_arg_start++;
1040 goto check_rest;
1041
1042 /* =========== PROFILING ========================== */
1043
1044 case 'P': /* detailed cost centre profiling (time/alloc) */
1045 case 'p': /* cost centre profiling (time/alloc) */
1046 OPTION_SAFE;
1047 PROFILING_BUILD_ONLY(
1048 switch (rts_argv[arg][2]) {
1049 case 'a':
1050 RtsFlags.CcFlags.doCostCentres = COST_CENTRES_ALL;
1051 if (rts_argv[arg][3] != '\0') {
1052 errorBelch("flag -Pa given an argument"
1053 " when none was expected: %s"
1054 ,rts_argv[arg]);
1055 error = rtsTrue;
1056 }
1057 break;
1058 case '\0':
1059 if (rts_argv[arg][1] == 'P') {
1060 RtsFlags.CcFlags.doCostCentres =
1061 COST_CENTRES_VERBOSE;
1062 } else {
1063 RtsFlags.CcFlags.doCostCentres =
1064 COST_CENTRES_SUMMARY;
1065 }
1066 break;
1067 default:
1068 unchecked_arg_start++;
1069 goto check_rest;
1070 }
1071 ) break;
1072
1073 case 'R':
1074 OPTION_SAFE;
1075 PROFILING_BUILD_ONLY(
1076 RtsFlags.ProfFlags.maxRetainerSetSize =
1077 atof(rts_argv[arg]+2);
1078 ) break;
1079 case 'L':
1080 OPTION_SAFE;
1081 PROFILING_BUILD_ONLY(
1082 RtsFlags.ProfFlags.ccsLength = atof(rts_argv[arg]+2);
1083 if(RtsFlags.ProfFlags.ccsLength <= 0) {
1084 bad_option(rts_argv[arg]);
1085 }
1086 ) break;
1087 case 'h': /* serial heap profile */
1088 #if !defined(PROFILING)
1089 OPTION_UNSAFE;
1090 switch (rts_argv[arg][2]) {
1091 case '\0':
1092 case 'T':
1093 RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CLOSURE_TYPE;
1094 break;
1095 default:
1096 errorBelch("invalid heap profile option: %s",rts_argv[arg]);
1097 error = rtsTrue;
1098 }
1099 #else
1100 OPTION_SAFE;
1101 PROFILING_BUILD_ONLY(
1102 switch (rts_argv[arg][2]) {
1103 case '\0':
1104 case 'C':
1105 case 'c':
1106 case 'M':
1107 case 'm':
1108 case 'D':
1109 case 'd':
1110 case 'Y':
1111 case 'y':
1112 case 'R':
1113 case 'r':
1114 case 'B':
1115 case 'b':
1116 if (rts_argv[arg][2] != '\0' && rts_argv[arg][3] != '\0') {
1117 {
1118 char *left = strchr(rts_argv[arg], '{');
1119 char *right = strrchr(rts_argv[arg], '}');
1120
1121 // curly braces are optional, for
1122 // backwards compat.
1123 if (left)
1124 left = left+1;
1125 else
1126 left = rts_argv[arg] + 3;
1127
1128 if (!right)
1129 right = rts_argv[arg] + strlen(rts_argv[arg]);
1130
1131 *right = '\0';
1132
1133 switch (rts_argv[arg][2]) {
1134 case 'c': // cost centre label select
1135 RtsFlags.ProfFlags.ccSelector = left;
1136 break;
1137 case 'C':
1138 RtsFlags.ProfFlags.ccsSelector = left;
1139 break;
1140 case 'M':
1141 case 'm': // cost centre module select
1142 RtsFlags.ProfFlags.modSelector = left;
1143 break;
1144 case 'D':
1145 case 'd': // closure descr select
1146 RtsFlags.ProfFlags.descrSelector = left;
1147 break;
1148 case 'Y':
1149 case 'y': // closure type select
1150 RtsFlags.ProfFlags.typeSelector = left;
1151 break;
1152 case 'R':
1153 case 'r': // retainer select
1154 RtsFlags.ProfFlags.retainerSelector = left;
1155 break;
1156 case 'B':
1157 case 'b': // biography select
1158 RtsFlags.ProfFlags.bioSelector = left;
1159 break;
1160 }
1161 }
1162 break;
1163 }
1164
1165 if (RtsFlags.ProfFlags.doHeapProfile != 0) {
1166 errorBelch("multiple heap profile options");
1167 error = rtsTrue;
1168 break;
1169 }
1170
1171 switch (rts_argv[arg][2]) {
1172 case '\0':
1173 case 'C':
1174 case 'c':
1175 RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CCS;
1176 break;
1177 case 'M':
1178 case 'm':
1179 RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_MOD;
1180 break;
1181 case 'D':
1182 case 'd':
1183 RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_DESCR;
1184 break;
1185 case 'Y':
1186 case 'y':
1187 RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_TYPE;
1188 break;
1189 case 'R':
1190 case 'r':
1191 RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_RETAINER;
1192 break;
1193 case 'B':
1194 case 'b':
1195 RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_LDV;
1196 break;
1197 }
1198 break;
1199
1200 default:
1201 errorBelch("invalid heap profile option: %s",rts_argv[arg]);
1202 error = rtsTrue;
1203 }
1204 )
1205 #endif /* PROFILING */
1206 break;
1207
1208 case 'i': /* heap sample interval */
1209 OPTION_UNSAFE;
1210 if (rts_argv[arg][2] == '\0') {
1211 /* use default */
1212 } else {
1213 RtsFlags.ProfFlags.heapProfileInterval =
1214 fsecondsToTime(atof(rts_argv[arg]+2));
1215 }
1216 break;
1217
1218 /* =========== CONCURRENT ========================= */
1219 case 'C': /* context switch interval */
1220 OPTION_UNSAFE;
1221 if (rts_argv[arg][2] == '\0')
1222 RtsFlags.ConcFlags.ctxtSwitchTime = 0;
1223 else {
1224 RtsFlags.ConcFlags.ctxtSwitchTime =
1225 fsecondsToTime(atof(rts_argv[arg]+2));
1226 }
1227 break;
1228
1229 case 'V': /* master tick interval */
1230 OPTION_UNSAFE;
1231 if (rts_argv[arg][2] == '\0') {
1232 // turns off ticks completely
1233 RtsFlags.MiscFlags.tickInterval = 0;
1234 } else {
1235 RtsFlags.MiscFlags.tickInterval =
1236 fsecondsToTime(atof(rts_argv[arg]+2));
1237 }
1238 break;
1239
1240 #if !defined(NOSMP)
1241 case 'N':
1242 OPTION_SAFE;
1243 THREADED_BUILD_ONLY(
1244 if (rts_argv[arg][2] == '\0') {
1245 #if defined(PROFILING)
1246 RtsFlags.ParFlags.nNodes = 1;
1247 #else
1248 RtsFlags.ParFlags.nNodes = getNumberOfProcessors();
1249 #endif
1250 } else {
1251 int nNodes;
1252 OPTION_SAFE; /* but see extra checks below... */
1253 nNodes = strtol(rts_argv[arg]+2, (char **) NULL, 10);
1254 if (nNodes <= 0) {
1255 errorBelch("bad value for -N");
1256 error = rtsTrue;
1257 }
1258 if (rtsOptsEnabled == RtsOptsSafeOnly &&
1259 nNodes > (int)getNumberOfProcessors()) {
1260 errorRtsOptsDisabled("Using large values for -N is not allowed by default. %s");
1261 stg_exit(EXIT_FAILURE);
1262 }
1263 RtsFlags.ParFlags.nNodes = (nat)nNodes;
1264 }
1265 ) break;
1266
1267 case 'g':
1268 OPTION_UNSAFE;
1269 THREADED_BUILD_ONLY(
1270 switch (rts_argv[arg][2]) {
1271 case '1':
1272 // backwards compat only
1273 RtsFlags.ParFlags.parGcEnabled = rtsFalse;
1274 break;
1275 default:
1276 errorBelch("unknown RTS option: %s",rts_argv[arg]);
1277 error = rtsTrue;
1278 break;
1279 }
1280 ) break;
1281
1282 case 'q':
1283 OPTION_UNSAFE;
1284 THREADED_BUILD_ONLY(
1285 switch (rts_argv[arg][2]) {
1286 case '\0':
1287 errorBelch("incomplete RTS option: %s",rts_argv[arg]);
1288 error = rtsTrue;
1289 break;
1290 case 'g':
1291 if (rts_argv[arg][3] == '\0') {
1292 RtsFlags.ParFlags.parGcEnabled = rtsFalse;
1293 } else {
1294 RtsFlags.ParFlags.parGcEnabled = rtsTrue;
1295 RtsFlags.ParFlags.parGcGen
1296 = strtol(rts_argv[arg]+3, (char **) NULL, 10);
1297 }
1298 break;
1299 case 'b':
1300 if (rts_argv[arg][3] == '\0') {
1301 RtsFlags.ParFlags.parGcLoadBalancingEnabled =
1302 rtsFalse;
1303 }
1304 else {
1305 RtsFlags.ParFlags.parGcLoadBalancingEnabled =
1306 rtsTrue;
1307 RtsFlags.ParFlags.parGcLoadBalancingGen
1308 = strtol(rts_argv[arg]+3, (char **) NULL, 10);
1309 }
1310 break;
1311 case 'i':
1312 RtsFlags.ParFlags.parGcNoSyncWithIdle
1313 = strtol(rts_argv[arg]+3, (char **) NULL, 10);
1314 break;
1315 case 'a':
1316 RtsFlags.ParFlags.setAffinity = rtsTrue;
1317 break;
1318 case 'm':
1319 RtsFlags.ParFlags.migrate = rtsFalse;
1320 break;
1321 case 'w':
1322 // -qw was removed; accepted for backwards compat
1323 break;
1324 default:
1325 errorBelch("unknown RTS option: %s",rts_argv[arg]);
1326 error = rtsTrue;
1327 break;
1328 }
1329 ) break;
1330 #endif
1331 /* =========== PARALLEL =========================== */
1332 case 'e':
1333 OPTION_UNSAFE;
1334 THREADED_BUILD_ONLY(
1335 if (rts_argv[arg][2] != '\0') {
1336 RtsFlags.ParFlags.maxLocalSparks
1337 = strtol(rts_argv[arg]+2, (char **) NULL, 10);
1338 if (RtsFlags.ParFlags.maxLocalSparks <= 0) {
1339 errorBelch("bad value for -e");
1340 error = rtsTrue;
1341 }
1342 }
1343 ) break;
1344
1345 /* =========== TICKY ============================== */
1346
1347 case 'r': /* Basic profiling stats */
1348 OPTION_SAFE;
1349 TICKY_BUILD_ONLY(
1350
1351 RtsFlags.TickyFlags.showTickyStats = rtsTrue;
1352
1353 {
1354 int r;
1355 if (rts_argv[arg][2] != '\0') {
1356 OPTION_UNSAFE;
1357 }
1358 r = openStatsFile(rts_argv[arg]+2,
1359 TICKY_FILENAME_FMT,
1360 &RtsFlags.TickyFlags.tickyFile);
1361 if (r == -1) { error = rtsTrue; }
1362 }
1363 ) break;
1364
1365 /* =========== TRACING ---------=================== */
1366
1367 case 'l':
1368 OPTION_SAFE;
1369 TRACING_BUILD_ONLY(
1370 RtsFlags.TraceFlags.tracing = TRACE_EVENTLOG;
1371 read_trace_flags(&rts_argv[arg][2]);
1372 );
1373 break;
1374
1375 case 'v':
1376 OPTION_SAFE;
1377 DEBUG_BUILD_ONLY(
1378 RtsFlags.TraceFlags.tracing = TRACE_STDERR;
1379 read_trace_flags(&rts_argv[arg][2]);
1380 );
1381 break;
1382
1383 /* =========== EXTENDED OPTIONS =================== */
1384
1385 case 'x': /* Extend the argument space */
1386 unchecked_arg_start++;
1387 switch(rts_argv[arg][2]) {
1388 case '\0':
1389 OPTION_SAFE;
1390 errorBelch("incomplete RTS option: %s",rts_argv[arg]);
1391 error = rtsTrue;
1392 break;
1393
1394 case 'b': /* heapBase in hex; undocumented */
1395 OPTION_UNSAFE;
1396 if (rts_argv[arg][3] != '\0') {
1397 RtsFlags.GcFlags.heapBase
1398 = strtol(rts_argv[arg]+3, (char **) NULL, 16);
1399 } else {
1400 errorBelch("-xb: requires argument");
1401 error = rtsTrue;
1402 }
1403 break;
1404
1405 #if defined(x86_64_HOST_ARCH)
1406 case 'm': /* linkerMemBase */
1407 OPTION_UNSAFE;
1408 if (rts_argv[arg][3] != '\0') {
1409 RtsFlags.MiscFlags.linkerMemBase
1410 = strtol(rts_argv[arg]+3, (char **) NULL, 16);
1411 if (RtsFlags.MiscFlags.linkerMemBase > 0x80000000) {
1412 errorBelch("-xm: value must be <80000000");
1413 error = rtsTrue;
1414 }
1415 } else {
1416 RtsFlags.MiscFlags.linkerMemBase = 0;
1417 }
1418 break;
1419 #endif
1420
1421 case 'c': /* Debugging tool: show current cost centre on
1422 an exception */
1423 OPTION_SAFE;
1424 PROFILING_BUILD_ONLY(
1425 RtsFlags.ProfFlags.showCCSOnException = rtsTrue;
1426 );
1427 unchecked_arg_start++;
1428 goto check_rest;
1429
1430 case 't': /* Include memory used by TSOs in a heap profile */
1431 OPTION_SAFE;
1432 PROFILING_BUILD_ONLY(
1433 RtsFlags.ProfFlags.includeTSOs = rtsTrue;
1434 );
1435 unchecked_arg_start++;
1436 goto check_rest;
1437
1438 /*
1439 * The option prefix '-xx' is reserved for future
1440 * extension. KSW 1999-11.
1441 */
1442
1443 case 'q':
1444 OPTION_UNSAFE;
1445 RtsFlags.GcFlags.allocLimitGrace
1446 = decodeSize(rts_argv[arg], 3, BLOCK_SIZE, HS_INT_MAX)
1447 / BLOCK_SIZE;
1448 break;
1449
1450 default:
1451 OPTION_SAFE;
1452 errorBelch("unknown RTS option: %s",rts_argv[arg]);
1453 error = rtsTrue;
1454 break;
1455 }
1456 break; /* defensive programming */
1457
1458 /* check the rest to be sure there is nothing afterwards.*/
1459 /* see Trac #9839 */
1460 check_rest:
1461 {
1462 /* start checking from the first unchecked position,
1463 * not from index 2*/
1464 /* see Trac #9839 */
1465 if (rts_argv[arg][unchecked_arg_start] != '\0') {
1466 errorBelch("flag -%c given an argument"
1467 " when none was expected: %s",
1468 rts_argv[arg][1],rts_argv[arg]);
1469 error = rtsTrue;
1470 }
1471 break;
1472 }
1473
1474 /* =========== OH DEAR ============================ */
1475 default:
1476 OPTION_SAFE;
1477 errorBelch("unknown RTS option: %s",rts_argv[arg]);
1478 error = rtsTrue;
1479 break;
1480 }
1481
1482 if (!option_checked) {
1483 /* Naughty! Someone didn't use OPTION_UNSAFE / OPTION_SAFE for
1484 an option above */
1485 errorBelch("Internal error in the RTS options parser");
1486 stg_exit(EXIT_FAILURE);
1487 }
1488 }
1489 }
1490
1491 if (error) errorUsage();
1492 }
1493
1494 /* -----------------------------------------------------------------------------
1495 * normaliseRtsOpts: Set some derived values, and make sure things are
1496 * within sensible ranges.
1497 * -------------------------------------------------------------------------- */
1498
1499 static void normaliseRtsOpts (void)
1500 {
1501 if (RtsFlags.MiscFlags.tickInterval < 0) {
1502 RtsFlags.MiscFlags.tickInterval = DEFAULT_TICK_INTERVAL;
1503 }
1504
1505 // If the master timer is disabled, turn off the other timers.
1506 if (RtsFlags.MiscFlags.tickInterval == 0) {
1507 RtsFlags.ConcFlags.ctxtSwitchTime = 0;
1508 RtsFlags.GcFlags.idleGCDelayTime = 0;
1509 RtsFlags.ProfFlags.heapProfileInterval = 0;
1510 }
1511
1512 // Determine what tick interval we should use for the RTS timer
1513 // by taking the shortest of the various intervals that we need to
1514 // monitor.
1515 if (RtsFlags.ConcFlags.ctxtSwitchTime > 0) {
1516 RtsFlags.MiscFlags.tickInterval =
1517 stg_min(RtsFlags.ConcFlags.ctxtSwitchTime,
1518 RtsFlags.MiscFlags.tickInterval);
1519 }
1520
1521 if (RtsFlags.GcFlags.idleGCDelayTime > 0) {
1522 RtsFlags.MiscFlags.tickInterval =
1523 stg_min(RtsFlags.GcFlags.idleGCDelayTime,
1524 RtsFlags.MiscFlags.tickInterval);
1525 }
1526
1527 if (RtsFlags.ProfFlags.heapProfileInterval > 0) {
1528 RtsFlags.MiscFlags.tickInterval =
1529 stg_min(RtsFlags.ProfFlags.heapProfileInterval,
1530 RtsFlags.MiscFlags.tickInterval);
1531 }
1532
1533 if (RtsFlags.ConcFlags.ctxtSwitchTime > 0) {
1534 RtsFlags.ConcFlags.ctxtSwitchTicks =
1535 RtsFlags.ConcFlags.ctxtSwitchTime /
1536 RtsFlags.MiscFlags.tickInterval;
1537 } else {
1538 RtsFlags.ConcFlags.ctxtSwitchTicks = 0;
1539 }
1540
1541 if (RtsFlags.ProfFlags.heapProfileInterval > 0) {
1542 RtsFlags.ProfFlags.heapProfileIntervalTicks =
1543 RtsFlags.ProfFlags.heapProfileInterval /
1544 RtsFlags.MiscFlags.tickInterval;
1545 } else {
1546 RtsFlags.ProfFlags.heapProfileIntervalTicks = 0;
1547 }
1548
1549 if (RtsFlags.GcFlags.stkChunkBufferSize >
1550 RtsFlags.GcFlags.stkChunkSize / 2) {
1551 errorBelch("stack chunk buffer size (-kb) must be less than 50%%\n"
1552 "of the stack chunk size (-kc)");
1553 errorUsage();
1554 }
1555 }
1556
1557 static void errorUsage (void)
1558 {
1559 const char **p;
1560
1561 fflush(stdout);
1562 for (p = usage_text; *p; p++)
1563 errorBelch("%s", *p);
1564 stg_exit(EXIT_FAILURE);
1565 }
1566
1567 static void
1568 stats_fprintf(FILE *f, char *s, ...)
1569 {
1570 va_list ap;
1571 va_start(ap,s);
1572 if (f == NULL) {
1573 vdebugBelch(s, ap);
1574 } else {
1575 vfprintf(f, s, ap);
1576 }
1577 va_end(ap);
1578 }
1579
1580 /* -----------------------------------------------------------------------------
1581 * openStatsFile: open a file in which to put some runtime stats
1582 * -------------------------------------------------------------------------- */
1583
1584 static int // return -1 on error
1585 openStatsFile (char *filename, // filename, or NULL
1586 const char *filename_fmt, // if filename == NULL, use
1587 // this fmt with sprintf to
1588 // generate the filename. %s
1589 // expands to the program name.
1590 FILE **file_ret) // return the FILE*
1591 {
1592 FILE *f = NULL;
1593
1594 if (strequal(filename, "stderr")
1595 || (filename_fmt == NULL && *filename == '\0')) {
1596 f = NULL; /* NULL means use debugBelch */
1597 } else {
1598 if (*filename != '\0') { /* stats file specified */
1599 f = fopen(filename,"w");
1600 } else {
1601 /* default <program>.<ext> */
1602 char stats_filename[STATS_FILENAME_MAXLEN];
1603 sprintf(stats_filename, filename_fmt, prog_name);
1604 f = fopen(stats_filename,"w");
1605 }
1606 if (f == NULL) {
1607 errorBelch("Can't open stats file %s\n", filename);
1608 return -1;
1609 }
1610 }
1611 *file_ret = f;
1612
1613 return 0;
1614 }
1615
1616 /* -----------------------------------------------------------------------------
1617 * initStatsFile: write a line to the file containing the program name
1618 * and the arguments it was invoked with.
1619 -------------------------------------------------------------------------- */
1620
1621 static void initStatsFile (FILE *f)
1622 {
1623 /* Write prog_argv and rts_argv into start of stats file */
1624 int count;
1625 for (count = 0; count < prog_argc; count++) {
1626 stats_fprintf(f, "%s ", prog_argv[count]);
1627 }
1628 stats_fprintf(f, "+RTS ");
1629 for (count = 0; count < rts_argc; count++)
1630 stats_fprintf(f, "%s ", rts_argv[count]);
1631 stats_fprintf(f, "\n");
1632 }
1633
1634 /* -----------------------------------------------------------------------------
1635 * decodeSize: parse a string containing a size, like 300K or 1.2M
1636 -------------------------------------------------------------------------- */
1637
1638 static StgWord64
1639 decodeSize(const char *flag, nat offset, StgWord64 min, StgWord64 max)
1640 {
1641 char c;
1642 const char *s;
1643 StgDouble m;
1644 StgWord64 val;
1645
1646 s = flag + offset;
1647
1648 if (!*s)
1649 {
1650 m = 0;
1651 }
1652 else
1653 {
1654 m = atof(s);
1655 c = s[strlen(s)-1];
1656
1657 if (c == 'g' || c == 'G')
1658 m *= 1024*1024*1024;
1659 else if (c == 'm' || c == 'M')
1660 m *= 1024*1024;
1661 else if (c == 'k' || c == 'K')
1662 m *= 1024;
1663 else if (c == 'w' || c == 'W')
1664 m *= sizeof(W_);
1665 }
1666
1667 val = (StgWord64)m;
1668
1669 if (m < 0 || val < min || val > max) {
1670 // printf doesn't like 64-bit format specs on Windows
1671 // apparently, so fall back to unsigned long.
1672 errorBelch("error in RTS option %s: size outside allowed range (%" FMT_Word " - %" FMT_Word ")", flag, (W_)min, (W_)max);
1673 stg_exit(EXIT_FAILURE);
1674 }
1675
1676 return val;
1677 }
1678
1679 #if defined(TRACING)
1680 static void read_trace_flags(char *arg)
1681 {
1682 char *c;
1683 rtsBool enabled = rtsTrue;
1684 /* Syntax for tracing flags currently looks like:
1685 *
1686 * -l To turn on eventlog tracing with default trace classes
1687 * -lx Turn on class 'x' (for some class listed below)
1688 * -l-x Turn off class 'x'
1689 * -la Turn on all classes
1690 * -l-a Turn off all classes
1691 *
1692 * This lets users say things like:
1693 * -la-p "all but sparks"
1694 * -l-ap "only sparks"
1695 */
1696
1697 /* Start by turning on the default tracing flags.
1698 *
1699 * Currently this is all the trace classes, except full-detail sparks.
1700 * Similarly, in future we might default to slightly less verbose
1701 * scheduler or GC tracing.
1702 */
1703 RtsFlags.TraceFlags.scheduler = rtsTrue;
1704 RtsFlags.TraceFlags.gc = rtsTrue;
1705 RtsFlags.TraceFlags.sparks_sampled = rtsTrue;
1706 RtsFlags.TraceFlags.user = rtsTrue;
1707
1708 for (c = arg; *c != '\0'; c++) {
1709 switch(*c) {
1710 case '\0':
1711 break;
1712 case '-':
1713 enabled = rtsFalse;
1714 break;
1715 case 'a':
1716 RtsFlags.TraceFlags.scheduler = enabled;
1717 RtsFlags.TraceFlags.gc = enabled;
1718 RtsFlags.TraceFlags.sparks_sampled = enabled;
1719 RtsFlags.TraceFlags.sparks_full = enabled;
1720 RtsFlags.TraceFlags.user = enabled;
1721 enabled = rtsTrue;
1722 break;
1723
1724 case 's':
1725 RtsFlags.TraceFlags.scheduler = enabled;
1726 enabled = rtsTrue;
1727 break;
1728 case 'p':
1729 RtsFlags.TraceFlags.sparks_sampled = enabled;
1730 enabled = rtsTrue;
1731 break;
1732 case 'f':
1733 RtsFlags.TraceFlags.sparks_full = enabled;
1734 enabled = rtsTrue;
1735 break;
1736 case 't':
1737 RtsFlags.TraceFlags.timestamp = enabled;
1738 enabled = rtsTrue;
1739 break;
1740 case 'g':
1741 RtsFlags.TraceFlags.gc = enabled;
1742 enabled = rtsTrue;
1743 break;
1744 case 'u':
1745 RtsFlags.TraceFlags.user = enabled;
1746 enabled = rtsTrue;
1747 break;
1748 default:
1749 errorBelch("unknown trace option: %c",*c);
1750 break;
1751 }
1752 }
1753 }
1754 #endif
1755
1756 static void GNU_ATTRIBUTE(__noreturn__)
1757 bad_option(const char *s)
1758 {
1759 errorBelch("bad RTS option: %s", s);
1760 stg_exit(EXIT_FAILURE);
1761 }
1762
1763 /* ----------------------------------------------------------------------------
1764 Copying and freeing argc/argv
1765 ------------------------------------------------------------------------- */
1766
1767 static char * copyArg(char *arg)
1768 {
1769 char *new_arg = stgMallocBytes(strlen(arg) + 1, "copyArg");
1770 strcpy(new_arg, arg);
1771 return new_arg;
1772 }
1773
1774 static char ** copyArgv(int argc, char *argv[])
1775 {
1776 int i;
1777 char **new_argv;
1778
1779 new_argv = stgCallocBytes(argc + 1, sizeof (char *), "copyArgv 1");
1780 for (i = 0; i < argc; i++) {
1781 new_argv[i] = copyArg(argv[i]);
1782 }
1783 new_argv[argc] = NULL;
1784 return new_argv;
1785 }
1786
1787 static void freeArgv(int argc, char *argv[])
1788 {
1789 int i;
1790 if (argv != NULL) {
1791 for (i = 0; i < argc; i++) {
1792 stgFree(argv[i]);
1793 }
1794 stgFree(argv);
1795 }
1796 }
1797
1798 /* -----------------------------------------------------------------------------
1799 Getting/Setting the program's arguments.
1800
1801 These are used by System.Environment, and parts of the RTS.
1802 -------------------------------------------------------------------------- */
1803
1804 void
1805 setProgName(char *argv[])
1806 {
1807 char *last_slash;
1808
1809 if (argv[0] == NULL) { // #7037
1810 prog_name = "";
1811 return;
1812 }
1813
1814 /* Remove directory from argv[0] -- default files in current directory */
1815 #if !defined(mingw32_HOST_OS)
1816 if ( (last_slash = (char *) strrchr(argv[0], '/')) != NULL ) {
1817 prog_name = last_slash+1;
1818 } else {
1819 prog_name = argv[0];
1820 }
1821 #else
1822 last_slash = argv[0] + (strlen(argv[0]) - 1);
1823 while ( last_slash > argv[0] ) {
1824 if ( *last_slash == '/' || *last_slash == '\\' ) {
1825 prog_name = last_slash+1;
1826 return;
1827 }
1828 last_slash--;
1829 }
1830 prog_name = argv[0];
1831 #endif
1832 }
1833
1834 void
1835 getProgArgv(int *argc, char **argv[])
1836 {
1837 if (argc) { *argc = prog_argc; }
1838 if (argv) { *argv = prog_argv; }
1839 }
1840
1841 void
1842 setProgArgv(int argc, char *argv[])
1843 {
1844 prog_argc = argc;
1845 prog_argv = copyArgv(argc,argv);
1846 setProgName(prog_argv);
1847 }
1848
1849 static void
1850 freeProgArgv(void)
1851 {
1852 freeArgv(prog_argc,prog_argv);
1853 prog_argc = 0;
1854 prog_argv = NULL;
1855 }
1856
1857 /* ----------------------------------------------------------------------------
1858 The full argv - a copy of the original program's argc/argv
1859 ------------------------------------------------------------------------- */
1860
1861 void
1862 setFullProgArgv(int argc, char *argv[])
1863 {
1864 full_prog_argc = argc;
1865 full_prog_argv = copyArgv(argc,argv);
1866 }
1867
1868 /* These functions record and recall the full arguments, including the
1869 +RTS ... -RTS options. The reason for adding them was so that the
1870 ghc-inplace program can pass /all/ the arguments on to the real ghc. */
1871 void
1872 getFullProgArgv(int *argc, char **argv[])
1873 {
1874 if (argc) { *argc = full_prog_argc; }
1875 if (argv) { *argv = full_prog_argv; }
1876 }
1877
1878 void
1879 freeFullProgArgv (void)
1880 {
1881 freeArgv(full_prog_argc, full_prog_argv);
1882 full_prog_argc = 0;
1883 full_prog_argv = NULL;
1884 }
1885
1886 /* ----------------------------------------------------------------------------
1887 The Win32 argv
1888 ------------------------------------------------------------------------- */
1889
1890 #if defined(mingw32_HOST_OS)
1891 void freeWin32ProgArgv (void);
1892
1893 void
1894 freeWin32ProgArgv (void)
1895 {
1896 int i;
1897
1898 if (win32_prog_argv != NULL) {
1899 for (i = 0; i < win32_prog_argc; i++) {
1900 stgFree(win32_prog_argv[i]);
1901 }
1902 stgFree(win32_prog_argv);
1903 }
1904
1905 win32_prog_argc = 0;
1906 win32_prog_argv = NULL;
1907 }
1908
1909 void
1910 getWin32ProgArgv(int *argc, wchar_t **argv[])
1911 {
1912 *argc = win32_prog_argc;
1913 *argv = win32_prog_argv;
1914 }
1915
1916 void
1917 setWin32ProgArgv(int argc, wchar_t *argv[])
1918 {
1919 int i;
1920
1921 freeWin32ProgArgv();
1922
1923 win32_prog_argc = argc;
1924 if (argv == NULL) {
1925 win32_prog_argv = NULL;
1926 return;
1927 }
1928
1929 win32_prog_argv = stgCallocBytes(argc + 1, sizeof (wchar_t *),
1930 "setWin32ProgArgv 1");
1931 for (i = 0; i < argc; i++) {
1932 win32_prog_argv[i] = stgMallocBytes((wcslen(argv[i]) + 1) * sizeof(wchar_t),
1933 "setWin32ProgArgv 2");
1934 wcscpy(win32_prog_argv[i], argv[i]);
1935 }
1936 win32_prog_argv[argc] = NULL;
1937 }
1938 #endif
1939
1940 /* ----------------------------------------------------------------------------
1941 The RTS argv
1942 ------------------------------------------------------------------------- */
1943
1944 static void
1945 freeRtsArgv(void)
1946 {
1947 freeArgv(rts_argc,rts_argv);
1948 rts_argc = 0;
1949 rts_argv = NULL;
1950 rts_argv_size = 0;
1951 }
1952
1953 /* ----------------------------------------------------------------------------
1954 All argvs
1955 ------------------------------------------------------------------------- */
1956
1957 void freeRtsArgs(void)
1958 {
1959 #if defined(mingw32_HOST_OS)
1960 freeWin32ProgArgv();
1961 #endif
1962 freeFullProgArgv();
1963 freeProgArgv();
1964 freeRtsArgv();
1965 }