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