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