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