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