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