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