Add a way to generate tracing events programmatically
[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.tracing       = TRACE_NONE;
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.tracing = TRACE_STDERR;
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.tracing = TRACE_EVENTLOG;
764                     break;
765                 case 's':
766                     RtsFlags.TraceFlags.tracing = TRACE_EVENTLOG;
767                     RtsFlags.TraceFlags.scheduler = rtsTrue;
768                     break;
769                 default:
770                     errorBelch("unknown RTS option: %s",rts_argv[arg]);
771                     error = rtsTrue;
772                     break;
773                 }
774 #else
775                 errorBelch("not built for: -eventlog");
776 #endif
777                 break;
778
779               case 'P': /* detailed cost centre profiling (time/alloc) */
780               case 'p': /* cost centre profiling (time/alloc) */
781                 PROFILING_BUILD_ONLY(
782                 switch (rts_argv[arg][2]) {
783                   case 'x':
784                     RtsFlags.CcFlags.doCostCentres = COST_CENTRES_XML;
785                     break;
786                   case 'a':
787                     RtsFlags.CcFlags.doCostCentres = COST_CENTRES_ALL;
788                     break;
789                   default:
790                       if (rts_argv[arg][1] == 'P') {
791                           RtsFlags.CcFlags.doCostCentres =
792                               COST_CENTRES_VERBOSE;
793                       } else {
794                           RtsFlags.CcFlags.doCostCentres =
795                               COST_CENTRES_SUMMARY;
796                       }
797                       break;
798                 }
799                 ) break;
800
801               case 'R':
802                   PROFILING_BUILD_ONLY(
803                       RtsFlags.ProfFlags.maxRetainerSetSize = atof(rts_argv[arg]+2);
804                   ) break;
805               case 'L':
806                   PROFILING_BUILD_ONLY(
807                       RtsFlags.ProfFlags.ccsLength = atof(rts_argv[arg]+2);
808                       if(RtsFlags.ProfFlags.ccsLength <= 0) {
809                         bad_option(rts_argv[arg]);
810                       }
811                   ) break;
812               case 'h': /* serial heap profile */
813 #if !defined(PROFILING)
814                 switch (rts_argv[arg][2]) {
815                   case '\0':
816                   case 'T':
817                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CLOSURE_TYPE;
818                     break;
819                   default:
820                     errorBelch("invalid heap profile option: %s",rts_argv[arg]);
821                     error = rtsTrue;
822                 }
823 #else
824                 PROFILING_BUILD_ONLY(
825                 switch (rts_argv[arg][2]) {
826                 case '\0':
827                 case 'C':
828                 case 'c':
829                 case 'M':
830                 case 'm':
831                 case 'D':
832                 case 'd':
833                 case 'Y':
834                 case 'y':
835                 case 'R':
836                 case 'r':
837                 case 'B':
838                 case 'b':
839                     if (rts_argv[arg][2] != '\0' && rts_argv[arg][3] != '\0') {
840                         {
841                             char *left  = strchr(rts_argv[arg], '{');
842                             char *right = strrchr(rts_argv[arg], '}');
843
844                             // curly braces are optional, for
845                             // backwards compat.
846                             if (left)
847                                 left = left+1;
848                             else
849                                 left = rts_argv[arg] + 3;
850
851                             if (!right)
852                                 right = rts_argv[arg] + strlen(rts_argv[arg]);
853
854                             *right = '\0';
855
856                             switch (rts_argv[arg][2]) {
857                             case 'c': // cost centre label select
858                                 RtsFlags.ProfFlags.ccSelector = left;
859                                 break;
860                             case 'C':
861                                 RtsFlags.ProfFlags.ccsSelector = left;
862                                 break;
863                             case 'M':
864                             case 'm': // cost centre module select
865                                 RtsFlags.ProfFlags.modSelector = left;
866                                 break;
867                             case 'D':
868                             case 'd': // closure descr select 
869                                 RtsFlags.ProfFlags.descrSelector = left;
870                                 break;
871                             case 'Y':
872                             case 'y': // closure type select
873                                 RtsFlags.ProfFlags.typeSelector = left;
874                                 break;
875                             case 'R':
876                             case 'r': // retainer select
877                                 RtsFlags.ProfFlags.retainerSelector = left;
878                                 break;
879                             case 'B':
880                             case 'b': // biography select
881                                 RtsFlags.ProfFlags.bioSelector = left;
882                                 break;
883                             }
884                         }
885                         break;
886                     }
887
888                     if (RtsFlags.ProfFlags.doHeapProfile != 0) {
889                         errorBelch("multiple heap profile options");
890                         error = rtsTrue;
891                         break;
892                     }
893
894                     switch (rts_argv[arg][2]) {
895                     case '\0':
896                     case 'C':
897                     case 'c':
898                         RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CCS;
899                         break;
900                     case 'M':
901                     case 'm':
902                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_MOD;
903                           break;
904                     case 'D':
905                     case 'd':
906                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_DESCR;
907                           break;
908                     case 'Y':
909                     case 'y':
910                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_TYPE;
911                           break;
912                     case 'R':
913                     case 'r':
914                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_RETAINER;
915                           break;
916                     case 'B':
917                     case 'b':
918                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_LDV;
919                           break;
920                     }
921                     break;
922                       
923                 default:
924                     errorBelch("invalid heap profile option: %s",rts_argv[arg]);
925                     error = rtsTrue;
926                 }
927                 ) 
928 #endif /* PROFILING */
929                 break;
930
931               case 'i': /* heap sample interval */
932                 if (rts_argv[arg][2] == '\0') {
933                   /* use default */
934                 } else {
935                     I_ cst; /* tmp */
936
937                     /* Convert to milliseconds */
938                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
939                     RtsFlags.ProfFlags.profileInterval = cst;
940                 }
941                 break;
942
943               /* =========== CONCURRENT ========================= */
944               case 'C': /* context switch interval */
945                 if (rts_argv[arg][2] == '\0')
946                     RtsFlags.ConcFlags.ctxtSwitchTime = 0;
947                 else {
948                     I_ cst; /* tmp */
949
950                     /* Convert to milliseconds */
951                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
952                     RtsFlags.ConcFlags.ctxtSwitchTime = cst;
953                 }
954                 break;
955
956               case 'V': /* master tick interval */
957                 if (rts_argv[arg][2] == '\0') {
958                     // turns off ticks completely
959                     RtsFlags.MiscFlags.tickInterval = 0;
960                 } else {
961                     I_ cst; /* tmp */
962
963                     /* Convert to milliseconds */
964                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
965                     RtsFlags.MiscFlags.tickInterval = cst;
966                 }
967                 break;
968
969 #if defined(THREADED_RTS) && !defined(NOSMP)
970               case 'N':
971                 THREADED_BUILD_ONLY(
972                 if (rts_argv[arg][2] == '\0') {
973 #if defined(PROFILING)
974                     RtsFlags.ParFlags.nNodes = 1;
975 #else
976                     RtsFlags.ParFlags.nNodes = getNumberOfProcessors();
977 #endif
978                 } else {
979                     RtsFlags.ParFlags.nNodes
980                       = strtol(rts_argv[arg]+2, (char **) NULL, 10);
981                     if (RtsFlags.ParFlags.nNodes <= 0) {
982                       errorBelch("bad value for -N");
983                       error = rtsTrue;
984                     }
985 #if defined(PROFILING)
986                     if (RtsFlags.ParFlags.nNodes > 1) {
987                         errorBelch("bad option %s: only -N1 is supported with profiling", rts_argv[arg]);
988                       error = rtsTrue;
989                     }
990 #endif
991                 }
992                 ) break;
993
994               case 'g':
995                 THREADED_BUILD_ONLY(
996                     switch (rts_argv[arg][2]) {
997                     case '1':
998                         // backwards compat only
999                         RtsFlags.ParFlags.parGcEnabled = rtsFalse;
1000                         break;
1001                     default:
1002                         errorBelch("unknown RTS option: %s",rts_argv[arg]);
1003                         error = rtsTrue;
1004                         break;
1005                     }
1006                     ) break;
1007
1008               case 'q':
1009                     switch (rts_argv[arg][2]) {
1010                     case '\0':
1011                         errorBelch("incomplete RTS option: %s",rts_argv[arg]);
1012                         error = rtsTrue;
1013                         break;
1014                     case 'g':
1015                         if (rts_argv[arg][3] == '\0') {
1016                             RtsFlags.ParFlags.parGcEnabled = rtsFalse;
1017                         } else {
1018                             RtsFlags.ParFlags.parGcEnabled = rtsTrue;
1019                             RtsFlags.ParFlags.parGcGen
1020                                 = strtol(rts_argv[arg]+3, (char **) NULL, 10);
1021                         }
1022                         break;
1023                     case 'b':
1024                         if (rts_argv[arg][3] == '\0') {
1025                             RtsFlags.ParFlags.parGcLoadBalancingEnabled = rtsFalse;
1026                         }
1027                         else {
1028                             RtsFlags.ParFlags.parGcLoadBalancingEnabled = rtsTrue;
1029                             RtsFlags.ParFlags.parGcLoadBalancingGen
1030                                 = strtol(rts_argv[arg]+3, (char **) NULL, 10);
1031                         }
1032                         break;
1033                     case 'a':
1034                         RtsFlags.ParFlags.setAffinity = rtsTrue;
1035                         break;
1036                     case 'm':
1037                         RtsFlags.ParFlags.migrate = rtsFalse;
1038                         break;
1039                     case 'w':
1040                         RtsFlags.ParFlags.wakeupMigrate = rtsTrue;
1041                         break;
1042                     default:
1043                         errorBelch("unknown RTS option: %s",rts_argv[arg]);
1044                         error = rtsTrue;
1045                         break;
1046                     }
1047                     break;
1048 #endif
1049               /* =========== PARALLEL =========================== */
1050               case 'e':
1051                 THREADED_BUILD_ONLY(
1052                 if (rts_argv[arg][2] != '\0') {
1053                     RtsFlags.ParFlags.maxLocalSparks
1054                       = strtol(rts_argv[arg]+2, (char **) NULL, 10);
1055                     if (RtsFlags.ParFlags.maxLocalSparks <= 0) {
1056                       errorBelch("bad value for -e");
1057                       error = rtsTrue;
1058                     }
1059                 }
1060                 ) break;
1061
1062               /* =========== TICKY ============================== */
1063
1064               case 'r': /* Basic profiling stats */
1065                 TICKY_BUILD_ONLY(
1066
1067                 RtsFlags.TickyFlags.showTickyStats = rtsTrue;
1068
1069                 { 
1070                     int r;
1071                     r = open_stats_file(arg, *argc, argv,
1072                                         *rts_argc, rts_argv, TICKY_FILENAME_FMT,
1073                                         &RtsFlags.TickyFlags.tickyFile);
1074                     if (r == -1) { error = rtsTrue; }
1075                 }
1076                 ) break;
1077
1078               /* =========== TRACING ---------=================== */
1079
1080               case 'v':
1081                 switch(rts_argv[arg][2]) {
1082 #ifdef TRACING
1083                 case '\0':
1084                     RtsFlags.TraceFlags.tracing = TRACE_STDERR;
1085                     break;
1086                 case 't':
1087                     RtsFlags.TraceFlags.timestamp = rtsTrue;
1088                     break;
1089 #endif
1090                 case 's':
1091                 case 'g':
1092                     // ignored for backwards-compat
1093                     break;
1094                 default:
1095                     errorBelch("unknown RTS option: %s",rts_argv[arg]);
1096                     error = rtsTrue;
1097                     break;
1098                 }
1099                 break;
1100
1101               /* =========== EXTENDED OPTIONS =================== */
1102
1103               case 'x': /* Extend the argument space */
1104                 switch(rts_argv[arg][2]) {
1105                   case '\0':
1106                     errorBelch("incomplete RTS option: %s",rts_argv[arg]);
1107                     error = rtsTrue;
1108                     break;
1109
1110                 case 'b': /* heapBase in hex; undocumented */
1111                     if (rts_argv[arg][3] != '\0') {
1112                         RtsFlags.GcFlags.heapBase
1113                             = strtol(rts_argv[arg]+3, (char **) NULL, 16);
1114                     } else {
1115                         errorBelch("-xb: requires argument");
1116                         error = rtsTrue;
1117                     }
1118                     break;
1119
1120 #if defined(x86_64_HOST_ARCH)
1121                 case 'm': /* linkerMemBase */
1122                     if (rts_argv[arg][3] != '\0') {
1123                         RtsFlags.MiscFlags.linkerMemBase
1124                             = strtol(rts_argv[arg]+3, (char **) NULL, 16);
1125                         if (RtsFlags.MiscFlags.linkerMemBase > 0x80000000) {
1126                             errorBelch("-xm: value must be <80000000");
1127                             error = rtsTrue;
1128                         }
1129                     } else {
1130                         RtsFlags.MiscFlags.linkerMemBase = 0;
1131                     }
1132                     break;
1133 #endif
1134
1135                 case 'c': /* Debugging tool: show current cost centre on an exception */
1136                     PROFILING_BUILD_ONLY(
1137                         RtsFlags.ProfFlags.showCCSOnException = rtsTrue;
1138                         );
1139                     break;
1140
1141                 case 't':  /* Include memory used by TSOs in a heap profile */
1142                     PROFILING_BUILD_ONLY(
1143                         RtsFlags.ProfFlags.includeTSOs = rtsTrue;
1144                         );
1145                     break;
1146
1147                   /* The option prefix '-xx' is reserved for future extension.  KSW 1999-11. */
1148
1149                   default:
1150                     errorBelch("unknown RTS option: %s",rts_argv[arg]);
1151                     error = rtsTrue;
1152                     break;
1153                 }
1154                 break;  /* defensive programming */
1155
1156               /* =========== OH DEAR ============================ */
1157               default:
1158                 errorBelch("unknown RTS option: %s",rts_argv[arg]);
1159                 error = rtsTrue;
1160                 break;
1161             }
1162         }
1163     }
1164
1165     if (RtsFlags.MiscFlags.tickInterval < 0) {
1166         RtsFlags.MiscFlags.tickInterval = 50;
1167     }
1168
1169     // If the master timer is disabled, turn off the other timers.
1170     if (RtsFlags.MiscFlags.tickInterval == 0) {
1171         RtsFlags.ConcFlags.ctxtSwitchTime  = 0;
1172         RtsFlags.GcFlags.idleGCDelayTime   = 0;
1173         RtsFlags.ProfFlags.profileInterval = 0;
1174     }
1175
1176     // Determine what tick interval we should use for the RTS timer
1177     // by taking the shortest of the various intervals that we need to
1178     // monitor.
1179     if (RtsFlags.ConcFlags.ctxtSwitchTime > 0) {
1180         RtsFlags.MiscFlags.tickInterval =
1181             stg_min(RtsFlags.ConcFlags.ctxtSwitchTime,
1182                     RtsFlags.MiscFlags.tickInterval);
1183     }
1184
1185     if (RtsFlags.GcFlags.idleGCDelayTime > 0) {
1186         RtsFlags.MiscFlags.tickInterval =
1187             stg_min(RtsFlags.GcFlags.idleGCDelayTime,
1188                     RtsFlags.MiscFlags.tickInterval);
1189     }
1190
1191     if (RtsFlags.ProfFlags.profileInterval > 0) {
1192         RtsFlags.MiscFlags.tickInterval =
1193             stg_min(RtsFlags.ProfFlags.profileInterval,
1194                     RtsFlags.MiscFlags.tickInterval);
1195     }
1196
1197     if (RtsFlags.ConcFlags.ctxtSwitchTime > 0) {
1198         RtsFlags.ConcFlags.ctxtSwitchTicks =
1199             RtsFlags.ConcFlags.ctxtSwitchTime /
1200             RtsFlags.MiscFlags.tickInterval;
1201     } else {
1202         RtsFlags.ConcFlags.ctxtSwitchTicks = 0;
1203     }
1204
1205     if (RtsFlags.ProfFlags.profileInterval > 0) {
1206         RtsFlags.ProfFlags.profileIntervalTicks =
1207             RtsFlags.ProfFlags.profileInterval / 
1208             RtsFlags.MiscFlags.tickInterval;
1209     } else {
1210         RtsFlags.ProfFlags.profileIntervalTicks = 0;
1211     }
1212
1213     if (error) {
1214         const char **p;
1215
1216         fflush(stdout);
1217         for (p = usage_text; *p; p++)
1218             errorBelch("%s", *p);
1219         stg_exit(EXIT_FAILURE);
1220     }
1221 }
1222
1223
1224 static void
1225 stats_fprintf(FILE *f, char *s, ...)
1226 {
1227     va_list ap;
1228     va_start(ap,s);
1229     if (f == NULL) {
1230         vdebugBelch(s, ap);
1231     } else {
1232         vfprintf(f, s, ap);
1233     }
1234     va_end(ap);
1235 }
1236
1237 static int              /* return -1 on error */
1238 open_stats_file (
1239     I_ arg,
1240     int argc, char *argv[],
1241     int rts_argc, char *rts_argv[],
1242     const char *FILENAME_FMT,
1243     FILE **file_ret)
1244 {
1245     FILE *f = NULL;
1246
1247     if (strequal(rts_argv[arg]+2, "stderr")
1248         || (FILENAME_FMT == NULL && rts_argv[arg][2] == '\0')) {
1249         f = NULL; /* NULL means use debugBelch */
1250     } else {
1251         if (rts_argv[arg][2] != '\0') {  /* stats file specified */
1252             f = fopen(rts_argv[arg]+2,"w");
1253         } else {
1254             char stats_filename[STATS_FILENAME_MAXLEN]; /* default <program>.<ext> */
1255             sprintf(stats_filename, FILENAME_FMT, argv[0]);
1256             f = fopen(stats_filename,"w");
1257         }
1258         if (f == NULL) {
1259             errorBelch("Can't open stats file %s\n", rts_argv[arg]+2);
1260             return -1;
1261         }
1262     }
1263     *file_ret = f;
1264
1265     {
1266         /* Write argv and rtsv into start of stats file */
1267         int count;
1268         for(count = 0; count < argc; count++) {
1269             stats_fprintf(f, "%s ", argv[count]);
1270         }
1271         stats_fprintf(f, "+RTS ");
1272         for(count = 0; count < rts_argc; count++)
1273             stats_fprintf(f, "%s ", rts_argv[count]);
1274         stats_fprintf(f, "\n");
1275     }
1276     return 0;
1277 }
1278
1279
1280
1281 static I_
1282 decode(const char *s)
1283 {
1284     I_ c;
1285     StgDouble m;
1286
1287     if (!*s)
1288         return 0;
1289
1290     m = atof(s);
1291     c = s[strlen(s)-1];
1292
1293     if (c == 'g' || c == 'G')
1294         m *= 1000*1000*1000;    /* UNchecked! */
1295     else if (c == 'm' || c == 'M')
1296         m *= 1000*1000;                 /* We do not use powers of 2 (1024) */
1297     else if (c == 'k' || c == 'K')      /* to avoid possible bad effects on */
1298         m *= 1000;                      /* a direct-mapped cache.           */ 
1299     else if (c == 'w' || c == 'W')
1300         m *= sizeof(W_);
1301
1302     return (I_)m;
1303 }
1304
1305 static void GNU_ATTRIBUTE(__noreturn__)
1306 bad_option(const char *s)
1307 {
1308   errorBelch("bad RTS option: %s", s);
1309   stg_exit(EXIT_FAILURE);
1310 }
1311
1312 /* -----------------------------------------------------------------------------
1313    Getting/Setting the program's arguments.
1314
1315    These are used by System.Environment, and parts of the RTS.
1316    -------------------------------------------------------------------------- */
1317
1318 void
1319 setProgName(char *argv[])
1320 {
1321     /* Remove directory from argv[0] -- default files in current directory */
1322 #if !defined(mingw32_HOST_OS)
1323     char *last_slash;
1324     if ( (last_slash = (char *) strrchr(argv[0], '/')) != NULL ) {
1325         prog_name = last_slash+1;
1326    } else {
1327         prog_name = argv[0];
1328    }
1329 #else
1330     char* last_slash = argv[0] + (strlen(argv[0]) - 1);
1331     while ( last_slash > argv[0] ) {
1332         if ( *last_slash == '/' || *last_slash == '\\' ) {
1333             prog_name = last_slash+1;
1334             return;
1335         }
1336         last_slash--;
1337     }
1338     prog_name = argv[0];
1339 #endif
1340 }
1341
1342 void
1343 getProgArgv(int *argc, char **argv[])
1344 {
1345     if (argc) { *argc = prog_argc; }
1346     if (argv) { *argv = prog_argv; }
1347 }
1348
1349 void
1350 setProgArgv(int argc, char *argv[])
1351 {
1352    /* Usually this is done by startupHaskell, so we don't need to call this. 
1353       However, sometimes Hugs wants to change the arguments which Haskell
1354       getArgs >>= ... will be fed.  So you can do that by calling here
1355       _after_ calling startupHaskell.
1356    */
1357    prog_argc = argc;
1358    prog_argv = argv;
1359    setProgName(prog_argv);
1360 }
1361
1362 /* These functions record and recall the full arguments, including the
1363    +RTS ... -RTS options. The reason for adding them was so that the
1364    ghc-inplace program can pass /all/ the arguments on to the real ghc. */
1365 void
1366 getFullProgArgv(int *argc, char **argv[])
1367 {
1368     if (argc) { *argc = full_prog_argc; }
1369     if (argv) { *argv = full_prog_argv; }
1370 }
1371
1372 void
1373 setFullProgArgv(int argc, char *argv[])
1374 {
1375     int i;
1376     full_prog_argc = argc;
1377     full_prog_argv = stgCallocBytes(argc + 1, sizeof (char *),
1378                                     "setFullProgArgv 1");
1379     for (i = 0; i < argc; i++) {
1380         full_prog_argv[i] = stgMallocBytes(strlen(argv[i]) + 1,
1381                                            "setFullProgArgv 2");
1382         strcpy(full_prog_argv[i], argv[i]);
1383     }
1384     full_prog_argv[argc] = NULL;
1385 }
1386