Add several new record features
[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 #include "RtsFlags.h"
13 #include "RtsUtils.h"
14 #include "Profiling.h"
15
16 #ifdef HAVE_CTYPE_H
17 #include <ctype.h>
18 #endif
19
20 #include <stdlib.h>
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 char   *prog_name = NULL; /* 'basename' of prog_argv[0] */
32 int     rts_argc = 0;  /* ditto */
33 char   *rts_argv[MAX_RTS_ARGS];
34
35 /*
36  * constants, used later 
37  */
38 #define RTS 1
39 #define PGM 0
40
41 #if defined(GRAN)
42
43 static char *gran_debug_opts_strs[] = {
44   "DEBUG (-bDe, -bD1): event_trace; printing event trace.\n",
45   "DEBUG (-bDE, -bD2): event_stats; printing event statistics.\n",
46   "DEBUG (-bDb, -bD4): bq; check blocking queues\n",
47   "DEBUG (-bDG, -bD8): pack; routines for (un-)packing graph structures.\n",
48   "DEBUG (-bDq, -bD16): checkSparkQ; check consistency of the spark queues.\n",
49   "DEBUG (-bDf, -bD32): thunkStealing; print forwarding of fetches.\n",
50   "DEBUG (-bDr, -bD64): randomSteal; stealing sparks/threads from random PEs.\n",
51   "DEBUG (-bDF, -bD128): findWork; searching spark-pools (local & remote), thread queues for work.\n",
52   "DEBUG (-bDu, -bD256): unused; currently unused flag.\n",
53   "DEBUG (-bDS, -bD512): pri; priority sparking or scheduling.\n",
54   "DEBUG (-bD:, -bD1024): checkLight; check GranSim-Light setup.\n",
55   "DEBUG (-bDo, -bD2048): sortedQ; check whether spark/thread queues are sorted.\n",
56   "DEBUG (-bDz, -bD4096): blockOnFetch; check for blocked on fetch.\n",
57   "DEBUG (-bDP, -bD8192): packBuffer; routines handling pack buffer (GranSim internal!).\n",
58   "DEBUG (-bDt, -bD16384): blockOnFetch_sanity; check for TSO asleep on fetch.\n",
59 };
60
61 /* one character codes for the available debug options */
62 static char gran_debug_opts_flags[] = {
63   'e', 'E', 'b', 'G', 'q', 'f', 'r', 'F', 'u', 'S', ':', 'o', 'z', 'P', 't'
64 };
65
66 #elif defined(PAR)
67
68 static char *par_debug_opts_strs[] = {
69   "DEBUG (-qDv, -qD1): verbose; be generally verbose with parallel related stuff.\n",
70   "DEBUG (-qDq, -qD2): bq; print blocking queues.\n",
71   "DEBUG (-qDs, -qD4): schedule; scheduling of parallel threads.\n",
72   "DEBUG (-qDe, -qD8): free; free messages.\n",
73   "DEBUG (-qDr, -qD16): resume; resume messages.\n",
74   "DEBUG (-qDw, -qD32): weight; print weights and distrib GC stuff.\n",
75   "DEBUG (-qDF, -qD64): fetch; fetch messages.\n",
76   // "DEBUG (-qDa, -qD128): ack; ack messages.\n",
77   "DEBUG (-qDf, -qD128): fish; fish messages.\n",
78   //"DEBUG (-qDo, -qD512): forward; forwarding messages to other PEs.\n",
79   "DEBUG (-qDl, -qD256): tables; print internal LAGA etc tables.\n",
80   "DEBUG (-qDo, -qD512): packet; packets and graph structures when packing.\n",
81   "DEBUG (-qDp, -qD1024): pack; packing and unpacking graphs.\n",
82   "DEBUG (-qDz, -qD2048): paranoia; ridiculously detailed output (excellent for filling a partition).\n"
83 };
84
85 /* one character codes for the available debug options */
86 static char par_debug_opts_flags[] = {
87   'v', 'q', 's', 'e', 'r', 'w', 'F', 'f', 'l', 'o', 'p', 'z'
88 };
89
90 #endif /* PAR */
91
92 /* -----------------------------------------------------------------------------
93    Static function decls
94    -------------------------------------------------------------------------- */
95
96 static int              /* return NULL on error */
97 open_stats_file (
98     I_ arg,
99     int argc, char *argv[],
100     int rts_argc, char *rts_argv[],
101     const char *FILENAME_FMT,
102     FILE **file_ret);
103
104 static I_ decode(const char *s);
105 static void bad_option(const char *s);
106
107 #if defined(GRAN)
108 static void enable_GranSimLight(void);
109 static void process_gran_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error);
110 static void set_GranSim_debug_options(nat n);
111 static void help_GranSim_debug_options(nat n);
112 #elif defined(PAR)
113 static void process_par_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error);
114 static void set_par_debug_options(nat n);
115 static void help_par_debug_options(nat n);
116 #endif
117
118 /* -----------------------------------------------------------------------------
119  * Command-line option parsing routines.
120  * ---------------------------------------------------------------------------*/
121
122 void initRtsFlagsDefaults(void)
123 {
124     RtsFlags.GcFlags.statsFile          = NULL;
125     RtsFlags.GcFlags.giveStats          = NO_GC_STATS;
126
127     RtsFlags.GcFlags.maxStkSize         = (8 * 1024 * 1024) / sizeof(W_);
128     RtsFlags.GcFlags.initialStkSize     = 1024 / sizeof(W_);
129
130     RtsFlags.GcFlags.minAllocAreaSize   = (512 * 1024)        / BLOCK_SIZE;
131     RtsFlags.GcFlags.minOldGenSize      = (1024 * 1024)       / BLOCK_SIZE;
132     RtsFlags.GcFlags.maxHeapSize        = 0;    /* off by default */
133     RtsFlags.GcFlags.heapSizeSuggestion = 0;    /* none */
134     RtsFlags.GcFlags.pcFreeHeap         = 3;    /* 3% */
135     RtsFlags.GcFlags.oldGenFactor       = 2;
136 #if defined(PAR)
137     /* A hack currently needed for GUM -- HWL */
138     RtsFlags.GcFlags.generations        = 1;
139     RtsFlags.GcFlags.steps              = 2;
140     RtsFlags.GcFlags.squeezeUpdFrames   = rtsFalse;
141 #else
142     RtsFlags.GcFlags.generations        = 2;
143     RtsFlags.GcFlags.steps              = 2;
144     RtsFlags.GcFlags.squeezeUpdFrames   = rtsTrue;
145 #endif
146     RtsFlags.GcFlags.compact            = rtsFalse;
147     RtsFlags.GcFlags.compactThreshold   = 30.0;
148 #ifdef RTS_GTK_FRONTPANEL
149     RtsFlags.GcFlags.frontpanel         = rtsFalse;
150 #endif
151     RtsFlags.GcFlags.idleGCDelayTime    = 300; /* millisecs */
152
153 #ifdef DEBUG
154     RtsFlags.DebugFlags.scheduler       = rtsFalse;
155     RtsFlags.DebugFlags.interpreter     = rtsFalse;
156     RtsFlags.DebugFlags.weak            = rtsFalse;
157     RtsFlags.DebugFlags.gccafs          = rtsFalse;
158     RtsFlags.DebugFlags.gc              = rtsFalse;
159     RtsFlags.DebugFlags.block_alloc     = rtsFalse;
160     RtsFlags.DebugFlags.sanity          = rtsFalse;
161     RtsFlags.DebugFlags.stable          = rtsFalse;
162     RtsFlags.DebugFlags.stm             = rtsFalse;
163     RtsFlags.DebugFlags.prof            = rtsFalse;
164     RtsFlags.DebugFlags.gran            = rtsFalse;
165     RtsFlags.DebugFlags.par             = rtsFalse;
166     RtsFlags.DebugFlags.linker          = rtsFalse;
167     RtsFlags.DebugFlags.squeeze         = rtsFalse;
168     RtsFlags.DebugFlags.hpc             = rtsFalse;
169 #endif
170
171 #if defined(PROFILING) || defined(PAR)
172     RtsFlags.CcFlags.doCostCentres      = 0;
173 #endif /* PROFILING or PAR */
174
175     RtsFlags.ProfFlags.doHeapProfile      = rtsFalse;
176     RtsFlags.ProfFlags.profileInterval    = 100;
177
178 #ifdef PROFILING
179     RtsFlags.ProfFlags.includeTSOs        = rtsFalse;
180     RtsFlags.ProfFlags.showCCSOnException = rtsFalse;
181     RtsFlags.ProfFlags.maxRetainerSetSize = 8;
182     RtsFlags.ProfFlags.ccsLength          = 25;
183     RtsFlags.ProfFlags.modSelector        = NULL;
184     RtsFlags.ProfFlags.descrSelector      = NULL;
185     RtsFlags.ProfFlags.typeSelector       = NULL;
186     RtsFlags.ProfFlags.ccSelector         = NULL;
187     RtsFlags.ProfFlags.ccsSelector        = NULL;
188     RtsFlags.ProfFlags.retainerSelector   = NULL;
189     RtsFlags.ProfFlags.bioSelector        = NULL;
190 #endif
191
192     RtsFlags.MiscFlags.tickInterval     = 50;  /* In milliseconds */
193     RtsFlags.ConcFlags.ctxtSwitchTime   = 50;  /* In milliseconds */
194
195     RtsFlags.MiscFlags.install_signal_handlers = rtsTrue;
196
197 #ifdef THREADED_RTS
198     RtsFlags.ParFlags.nNodes            = 1;
199     RtsFlags.ParFlags.migrate           = rtsTrue;
200     RtsFlags.ParFlags.wakeupMigrate     = rtsFalse;
201 #endif
202
203 #ifdef PAR
204     RtsFlags.ParFlags.ParStats.Full       = rtsFalse;
205     RtsFlags.ParFlags.ParStats.Suppressed = rtsFalse;
206     RtsFlags.ParFlags.ParStats.Binary     = rtsFalse;
207     RtsFlags.ParFlags.ParStats.Sparks     = rtsFalse;
208     RtsFlags.ParFlags.ParStats.Heap       = rtsFalse;
209     RtsFlags.ParFlags.ParStats.NewLogfile = rtsFalse;
210     RtsFlags.ParFlags.ParStats.Global     = rtsFalse;
211
212     RtsFlags.ParFlags.outputDisabled    = rtsFalse;
213 #ifdef DIST
214     RtsFlags.ParFlags.doFairScheduling  = rtsTrue;  /* fair sched by def */
215 #else
216     RtsFlags.ParFlags.doFairScheduling  = rtsFalse;  /* unfair sched by def */
217 #endif
218     RtsFlags.ParFlags.packBufferSize    = 1024;
219     RtsFlags.ParFlags.thunksToPack      = 1; /* 0 ... infinity; */
220     RtsFlags.ParFlags.globalising       = 1; /* 0 ... everything */
221     RtsFlags.ParFlags.maxThreads        = 1024;
222     RtsFlags.ParFlags.maxFishes        = MAX_FISHES;
223     RtsFlags.ParFlags.fishDelay         = FISH_DELAY;
224 #endif
225
226 #if defined(PAR) || defined(THREADED_RTS)
227     RtsFlags.ParFlags.maxLocalSparks    = 4096;
228 #endif /* PAR || THREADED_RTS */
229
230 #if defined(GRAN)
231     /* ToDo: check defaults for GranSim and GUM */
232     RtsFlags.GcFlags.maxStkSize         = (8 * 1024 * 1024) / sizeof(W_);
233     RtsFlags.GcFlags.initialStkSize     = 1024 / sizeof(W_);
234
235     RtsFlags.GranFlags.maxThreads       = 65536; // refers to mandatory threads
236     RtsFlags.GranFlags.GranSimStats.Full        = rtsFalse;
237     RtsFlags.GranFlags.GranSimStats.Suppressed  = rtsFalse;
238     RtsFlags.GranFlags.GranSimStats.Binary      = rtsFalse;
239     RtsFlags.GranFlags.GranSimStats.Sparks      = rtsFalse;
240     RtsFlags.GranFlags.GranSimStats.Heap        = rtsFalse;
241     RtsFlags.GranFlags.GranSimStats.NewLogfile  = rtsFalse;
242     RtsFlags.GranFlags.GranSimStats.Global      = rtsFalse;
243
244     RtsFlags.GranFlags.packBufferSize   = 1024;
245     RtsFlags.GranFlags.packBufferSize_internal = GRANSIM_DEFAULT_PACK_BUFFER_SIZE;
246
247     RtsFlags.GranFlags.proc         = MAX_PROC;
248     RtsFlags.GranFlags.Fishing      = rtsFalse;
249     RtsFlags.GranFlags.maxFishes   = MAX_FISHES;
250     RtsFlags.GranFlags.time_slice   = GRAN_TIME_SLICE;
251     RtsFlags.GranFlags.Light        = rtsFalse;
252
253     RtsFlags.GranFlags.Costs.latency =             LATENCY;          
254     RtsFlags.GranFlags.Costs.additional_latency =  ADDITIONAL_LATENCY; 
255     RtsFlags.GranFlags.Costs.fetchtime =           FETCHTIME; 
256     RtsFlags.GranFlags.Costs.lunblocktime =        LOCALUNBLOCKTIME; 
257     RtsFlags.GranFlags.Costs.gunblocktime =        GLOBALUNBLOCKTIME;
258     RtsFlags.GranFlags.Costs.mpacktime =           MSGPACKTIME;      
259     RtsFlags.GranFlags.Costs.munpacktime =         MSGUNPACKTIME;
260     RtsFlags.GranFlags.Costs.mtidytime =           MSGTIDYTIME;
261
262     RtsFlags.GranFlags.Costs.threadcreatetime =         THREADCREATETIME;
263     RtsFlags.GranFlags.Costs.threadqueuetime =          THREADQUEUETIME;
264     RtsFlags.GranFlags.Costs.threaddescheduletime =     THREADDESCHEDULETIME;
265     RtsFlags.GranFlags.Costs.threadscheduletime =       THREADSCHEDULETIME;
266     RtsFlags.GranFlags.Costs.threadcontextswitchtime =  THREADCONTEXTSWITCHTIME;
267
268     RtsFlags.GranFlags.Costs.arith_cost =         ARITH_COST;       
269     RtsFlags.GranFlags.Costs.branch_cost =        BRANCH_COST; 
270     RtsFlags.GranFlags.Costs.load_cost =          LOAD_COST;        
271     RtsFlags.GranFlags.Costs.store_cost =         STORE_COST; 
272     RtsFlags.GranFlags.Costs.float_cost =         FLOAT_COST;       
273
274     RtsFlags.GranFlags.Costs.heapalloc_cost =     HEAPALLOC_COST;
275
276     RtsFlags.GranFlags.Costs.pri_spark_overhead = PRI_SPARK_OVERHEAD;        
277     RtsFlags.GranFlags.Costs.pri_sched_overhead = PRI_SCHED_OVERHEAD;        
278
279     RtsFlags.GranFlags.DoFairSchedule           = rtsFalse;             
280     RtsFlags.GranFlags.DoAsyncFetch             = rtsFalse;        
281     RtsFlags.GranFlags.DoStealThreadsFirst      = rtsFalse;        
282     RtsFlags.GranFlags.DoAlwaysCreateThreads    = rtsFalse;      
283     RtsFlags.GranFlags.DoBulkFetching           = rtsFalse;             
284     RtsFlags.GranFlags.DoThreadMigration        = rtsFalse;          
285     RtsFlags.GranFlags.FetchStrategy            = 2;                     
286     RtsFlags.GranFlags.PreferSparksOfLocalNodes = rtsFalse;   
287     RtsFlags.GranFlags.DoPrioritySparking       = rtsFalse;         
288     RtsFlags.GranFlags.DoPriorityScheduling     = rtsFalse;       
289     RtsFlags.GranFlags.SparkPriority            = 0;
290     RtsFlags.GranFlags.SparkPriority2           = 0; 
291     RtsFlags.GranFlags.RandomPriorities         = rtsFalse;           
292     RtsFlags.GranFlags.InversePriorities        = rtsFalse;          
293     RtsFlags.GranFlags.IgnorePriorities         = rtsFalse;           
294     RtsFlags.GranFlags.ThunksToPack             = 0;                      
295     RtsFlags.GranFlags.RandomSteal              = rtsTrue;
296 #endif
297
298 #ifdef TICKY_TICKY
299     RtsFlags.TickyFlags.showTickyStats   = rtsFalse;
300     RtsFlags.TickyFlags.tickyFile        = NULL;
301 #endif
302
303     RtsFlags.TraceFlags.timestamp       = rtsFalse;
304     RtsFlags.TraceFlags.sched           = rtsFalse;
305
306 #ifdef USE_PAPI
307     /* By default no special measurements taken */
308     RtsFlags.PapiFlags.eventType        = 0;
309 #endif
310 }
311
312 static const char *
313 usage_text[] = {
314 "",
315 "Usage: <prog> <args> [+RTS <rtsopts> | -RTS <args>] ... --RTS <args>",
316 "",
317 "   +RTS    Indicates run time system options follow",
318 "   -RTS    Indicates program arguments follow",
319 "  --RTS    Indicates that ALL subsequent arguments will be given to the",
320 "           program (including any of these RTS flags)",
321 "",
322 "The following run time system options are available:",
323 "",
324 "  -?       Prints this message and exits; the program is not executed",
325 "",
326 "  -K<size> Sets the maximum stack size (default 8M)  Egs: -K32k   -K512k",
327 "  -k<size> Sets the initial thread stack size (default 1k)  Egs: -k4k   -k2m",
328 "",
329 "  -A<size> Sets the minimum allocation area size (default 256k) Egs: -A1m -A10k",
330 "  -M<size> Sets the maximum heap size (default unlimited)  Egs: -M256k -M1G",
331 "  -H<size> Sets the minimum heap size (default 0M)   Egs: -H24m  -H1G",
332 "  -m<n>    Minimum % of heap which must be available (default 3%)",
333 "  -G<n>    Number of generations (default: 2)",
334 "  -T<n>    Number of steps in younger generations (default: 2)",
335 "  -c<n>    Auto-enable compaction of the oldest generation when live data is",
336 "           at least <n>% of the maximum heap size set with -M (default: 30%)",
337 "  -c       Enable compaction for all major collections",
338 #if defined(THREADED_RTS)
339 "  -I<sec>  Perform full GC after <sec> idle time (default: 0.3, 0 == off)",
340 #endif
341 "",
342 "  -t<file> One-line GC statistics  (default file: <program>.stat)",
343 "  -s<file> Summary  GC statistics  (with -Sstderr going to stderr)",
344 "  -S<file> Detailed GC statistics",
345 #ifdef RTS_GTK_FRONTPANEL
346 "  -f       Display front panel (requires X11 & GTK+)",
347 #endif
348 "",
349 "",
350 "  -Z       Don't squeeze out update frames on stack overflow",
351 "  -B       Sound the bell at the start of each garbage collection",
352 #if defined(PROFILING) || defined(PAR)
353 "",
354 "  -px      Time/allocation profile (XML)  (output file <program>.prof)",
355 "  -p       Time/allocation profile        (output file <program>.prof)",
356 "  -P       More detailed Time/Allocation profile",
357 "  -Pa      Give information about *all* cost centres",
358
359 # if defined(PROFILING)
360 "",
361 "  -hx            Heap residency profile (XML)   (output file <program>.prof)",
362 "  -h<break-down> Heap residency profile (hp2ps) (output file <program>.hp)",
363 "     break-down: c = cost centre stack (default)",
364 "                 m = module",
365 "                 d = closure description",
366 "                 y = type description",
367 "                 r = retainer",
368 "                 b = biography (LAG,DRAG,VOID,USE)",
369 "  A subset of closures may be selected thusly:",
370 "    -hc<cc>,...  specific cost centre(s) (top of stack only)",
371 "    -hC<cc>,...  specific cost centre(s) (anywhere in stack)",
372 "    -hm<mod>...  all cost centres from the specified modules(s)",
373 "    -hd<des>,... closures with specified closure descriptions",
374 "    -hy<typ>...  closures with specified type descriptions",
375 "    -hr<cc>...   closures with specified retainers",
376 "    -hb<bio>...  closures with specified biographies (lag,drag,void,use)",
377 "",
378 "  -R<size>       Set the maximum retainer set size (default: 8)",
379 "", 
380 "  -L<chars>      Maximum length of a cost-centre stack in a heap profile",
381 "                 (default: 25)",
382 "",
383 "  -xt            Include threads (TSOs) in a heap profile",
384 "",
385 "  -xc      Show current cost centre stack on raising an exception",
386 "",
387 # endif
388 #endif /* PROFILING or PAR */
389 #if !defined(PROFILING)
390 "",
391 "  -hT      Heap residency profile (output file <program>.hp)",
392 #endif
393 "  -i<sec>  Time between heap samples (seconds, default: 0.1)",
394 "",
395 #if defined(TICKY_TICKY)
396 "  -r<file>  Produce ticky-ticky statistics (with -rstderr for stderr)",
397 "",
398 #endif
399 #if defined(PAR)
400 "  -N<n>     Use <n> PVMish processors in parallel (default: 2)",
401 /* NB: the -N<n> is implemented by the driver!! */
402 #endif
403 "  -C<secs>  Context-switch interval in seconds.",
404 "            0 or no argument means switch as often as possible.",
405 "            Default: 0.02 sec; resolution is set by -V below.",
406 "  -V<secs>  Master tick interval in seconds.",
407 "            This sets the resolution for -C and the profile timer -i.",
408 "            Default: 0.02 sec.",
409 "",
410 "  -vs       Trace scheduler events (see also -Ds with -debug)",
411 "  -vt       Time-stamp trace messages",
412 "",
413 #if defined(DEBUG)
414 "  -Ds  DEBUG: scheduler",
415 "  -Di  DEBUG: interpreter",
416 "  -Dw  DEBUG: weak",
417 "  -DG  DEBUG: gccafs",
418 "  -Dg  DEBUG: gc",
419 "  -Db  DEBUG: block",
420 "  -DS  DEBUG: sanity",
421 "  -Dt  DEBUG: stable",
422 "  -Dp  DEBUG: prof",
423 "  -Dr  DEBUG: gran",
424 "  -DP  DEBUG: par",
425 "  -Dl  DEBUG: linker",
426 "  -Dm  DEBUG: stm",
427 "  -Dz  DEBUG: stack squezing",
428 "  -Dc  DEBUG: program coverage",
429 "",
430 #endif /* DEBUG */
431 #if defined(THREADED_RTS) && !defined(NOSMP)
432 "  -N<n>     Use <n> OS threads (default: 1)",
433 "  -qm       Don't automatically migrate threads between CPUs",
434 "  -qw       Migrate a thread to the current CPU when it is woken up",
435 #endif
436 "  --install-signal-handlers=<yes|no>",
437 "            Install signal handlers (default: yes)",
438 #if defined(THREADED_RTS) || defined(PAR)
439 "  -e<size>  Size of spark pools (default 100)",
440 #endif
441 #if defined(PAR)
442 "  -t<num>   Set maximum number of advisory threads per PE (default 32)",
443 "  -qP       Enable activity profile (output files in ~/<program>*.gr)",
444 "  -qQ<size> Set pack-buffer size (default: 1024)",
445 "  -qd       Turn on PVM-ish debugging",
446 "  -qO       Disable output for performance measurement",
447 #endif
448 #if defined(THREADED_RTS) || defined(PAR)
449 "  -e<n>     Maximum number of outstanding local sparks (default: 4096)",
450 #endif
451 #if defined(PAR)
452 "  -d        Turn on PVM-ish debugging",
453 "  -O        Disable output for performance measurement",
454 #endif /* PAR */
455 #if defined(GRAN)  /* ToDo: fill in decent Docu here */
456 "  -b...     All GranSim options start with -b; see GranSim User's Guide for details",
457 #endif
458 #if defined(USE_PAPI)
459 "  -aX       CPU performance counter measurements using PAPI",
460 "            (use with the -s<file> option).  X is one of:",
461 "",
462 /* "            y - cycles", */
463 "            1 - level 1 cache misses",
464 "            2 - level 2 cache misses",
465 "            b - branch mispredictions",
466 "            s - stalled cycles",
467 "            e - cache miss and branch misprediction events",
468 #endif
469 "",
470 "RTS options may also be specified using the GHCRTS environment variable.",
471 "",
472 "Other RTS options may be available for programs compiled a different way.",
473 "The GHC User's Guide has full details.",
474 "",
475 0
476 };
477
478 STATIC_INLINE rtsBool
479 strequal(const char *a, const char * b)
480 {
481     return(strcmp(a, b) == 0);
482 }
483
484 static void
485 splitRtsFlags(char *s, int *rts_argc, char *rts_argv[])
486 {
487     char *c1, *c2;
488
489     c1 = s;
490     do {
491         while (isspace(*c1)) { c1++; };
492         c2 = c1;
493         while (!isspace(*c2) && *c2 != '\0') { c2++; };
494         
495         if (c1 == c2) { break; }
496         
497         if (*rts_argc < MAX_RTS_ARGS-1) {
498             s = stgMallocBytes(c2-c1+1, "RtsFlags.c:splitRtsFlags()");
499             strncpy(s, c1, c2-c1);
500             s[c2-c1] = '\0';
501             rts_argv[(*rts_argc)++] = s;
502         } else {
503             barf("too many RTS arguments (max %d)", MAX_RTS_ARGS-1);
504         }
505         
506         c1 = c2;
507     } while (*c1 != '\0');
508 }
509     
510 void
511 setupRtsFlags(int *argc, char *argv[], int *rts_argc, char *rts_argv[])
512 {
513     rtsBool error = rtsFalse;
514     I_ mode;
515     I_ arg, total_arg;
516
517     setProgName (argv);
518     total_arg = *argc;
519     arg = 1;
520
521     *argc = 1;
522     *rts_argc = 0;
523
524     // process arguments from the ghc_rts_opts global variable first.
525     // (arguments from the GHCRTS environment variable and the command
526     // line override these).
527     {
528         if (ghc_rts_opts != NULL) {
529             splitRtsFlags(ghc_rts_opts, rts_argc, rts_argv);
530         }
531     }
532
533     // process arguments from the GHCRTS environment variable next
534     // (arguments from the command line override these).
535     {
536         char *ghc_rts = getenv("GHCRTS");
537
538         if (ghc_rts != NULL) {
539             splitRtsFlags(ghc_rts, rts_argc, rts_argv);
540         }
541     }
542
543     // Split arguments (argv) into PGM (argv) and RTS (rts_argv) parts
544     //   argv[0] must be PGM argument -- leave in argv
545
546     for (mode = PGM; arg < total_arg; arg++) {
547         // The '--RTS' argument disables all future +RTS ... -RTS processing.
548         if (strequal("--RTS", argv[arg])) {
549             arg++;
550             break;
551         }
552         // The '--' argument is passed through to the program, but
553         // disables all further +RTS ... -RTS processing.
554         else if (strequal("--", argv[arg])) {
555             break;
556         }
557         else if (strequal("+RTS", argv[arg])) {
558             mode = RTS;
559         }
560         else if (strequal("-RTS", argv[arg])) {
561             mode = PGM;
562         }
563         else if (mode == RTS && *rts_argc < MAX_RTS_ARGS-1) {
564             rts_argv[(*rts_argc)++] = argv[arg];
565         }
566         else if (mode == PGM) {
567             argv[(*argc)++] = argv[arg];
568         }
569         else {
570           barf("too many RTS arguments (max %d)", MAX_RTS_ARGS-1);
571         }
572     }
573     // process remaining program arguments
574     for (; arg < total_arg; arg++) {
575         argv[(*argc)++] = argv[arg];
576     }
577     argv[*argc] = (char *) 0;
578     rts_argv[*rts_argc] = (char *) 0;
579
580     // Process RTS (rts_argv) part: mainly to determine statsfile
581     for (arg = 0; arg < *rts_argc; arg++) {
582         if (rts_argv[arg][0] != '-') {
583             fflush(stdout);
584             errorBelch("unexpected RTS argument: %s", rts_argv[arg]);
585             error = rtsTrue;
586
587         } else {
588             switch(rts_argv[arg][1]) {
589
590               /* process: general args, then PROFILING-only ones,
591                  then CONCURRENT-only, PARallel-only, GRAN-only,
592                  TICKY-only (same order as defined in RtsFlags.lh);
593                  within those groups, mostly in case-insensitive
594                  alphabetical order.
595                  Final group is x*, which allows for more options.
596               */
597
598 #ifdef TICKY_TICKY
599 # define TICKY_BUILD_ONLY(x) x
600 #else
601 # define TICKY_BUILD_ONLY(x) \
602 errorBelch("not built for: ticky-ticky stats"); \
603 error = rtsTrue;
604 #endif
605
606 #if defined(PROFILING) 
607 # define COST_CENTRE_USING_BUILD_ONLY(x) x
608 #else
609 # define COST_CENTRE_USING_BUILD_ONLY(x) \
610 errorBelch("not built for: -prof or -parallel"); \
611 error = rtsTrue;
612 #endif
613
614 #ifdef PROFILING
615 # define PROFILING_BUILD_ONLY(x)   x
616 #else
617 # define PROFILING_BUILD_ONLY(x) \
618 errorBelch("not built for: -prof"); \
619 error = rtsTrue;
620 #endif
621
622 #ifdef PAR
623 # define PAR_BUILD_ONLY(x)      x
624 #else
625 # define PAR_BUILD_ONLY(x) \
626 errorBelch("not built for: -parallel"); \
627 error = rtsTrue;
628 #endif
629
630 #ifdef THREADED_RTS
631 # define THREADED_BUILD_ONLY(x)      x
632 #else
633 # define THREADED_BUILD_ONLY(x) \
634 errorBelch("not built for: -smp"); \
635 error = rtsTrue;
636 #endif
637
638 #if defined(THREADED_RTS) || defined(PAR)
639 # define PAR_OR_THREADED_BUILD_ONLY(x)      x
640 #else
641 # define PAR_OR_THREADED_BUILD_ONLY(x) \
642 errorBelch("not built for: -parallel or -smp"); \
643 error = rtsTrue;
644 #endif
645
646 #ifdef GRAN
647 # define GRAN_BUILD_ONLY(x)     x
648 #else
649 # define GRAN_BUILD_ONLY(x) \
650 errorBelch("not built for: -gransim"); \
651 error = rtsTrue;
652 #endif
653
654               /* =========== GENERAL ========================== */
655               case '?':
656                 error = rtsTrue;
657                 break;
658
659               /* This isn't going to allow us to keep related options
660                  together as we add more --* flags. We really need a
661                  proper options parser. */
662               case '-':
663                   if (strequal("install-signal-handlers=yes",
664                                &rts_argv[arg][2])) {
665                       RtsFlags.MiscFlags.install_signal_handlers = rtsTrue;
666                   }
667                   else if (strequal("install-signal-handlers=no",
668                                &rts_argv[arg][2])) {
669                       RtsFlags.MiscFlags.install_signal_handlers = rtsFalse;
670                   }
671                   else {
672                       errorBelch("unknown RTS option: %s",rts_argv[arg]);
673                       error = rtsTrue;
674                   }
675                   break;
676               case 'A':
677                 RtsFlags.GcFlags.minAllocAreaSize
678                   = decode(rts_argv[arg]+2) / BLOCK_SIZE;
679                 if (RtsFlags.GcFlags.minAllocAreaSize <= 0) {
680                   bad_option(rts_argv[arg]);
681                 }
682                 break;
683
684 #ifdef USE_PAPI
685               case 'a':
686                 switch(rts_argv[arg][2]) {
687                 case '1':
688                   RtsFlags.PapiFlags.eventType = PAPI_FLAG_CACHE_L1;
689                   break;
690                 case '2':
691                   RtsFlags.PapiFlags.eventType = PAPI_FLAG_CACHE_L2;
692                   break;
693                 case 'b':
694                   RtsFlags.PapiFlags.eventType = PAPI_FLAG_BRANCH;
695                   break;
696                 case 's':
697                   RtsFlags.PapiFlags.eventType = PAPI_FLAG_STALLS;
698                   break;
699                 case 'e':
700                   RtsFlags.PapiFlags.eventType = PAPI_FLAG_CB_EVENTS;
701                   break;
702                 default:
703                   bad_option( rts_argv[arg] );
704                 }
705                 break;
706 #endif
707
708               case 'B':
709                 RtsFlags.GcFlags.ringBell = rtsTrue;
710                 break;
711
712               case 'c':
713                   if (rts_argv[arg][2] != '\0') {
714                       RtsFlags.GcFlags.compactThreshold =
715                           atof(rts_argv[arg]+2);
716                   } else {
717                       RtsFlags.GcFlags.compact = rtsTrue;
718                   }
719                   break;
720
721               case 'F':
722                 RtsFlags.GcFlags.oldGenFactor = atof(rts_argv[arg]+2);
723               
724                 if (RtsFlags.GcFlags.oldGenFactor < 0)
725                   bad_option( rts_argv[arg] );
726                 break;
727               
728 #ifdef DEBUG
729               case 'D':
730               { 
731                   char *c;
732
733                   for (c  = rts_argv[arg] + 2; *c != '\0'; c++) {
734                       switch (*c) {
735                       case 's':
736                           RtsFlags.DebugFlags.scheduler = rtsTrue;
737                           break;
738                       case 'i':
739                           RtsFlags.DebugFlags.interpreter = rtsTrue;
740                           break;
741                       case 'w':
742                           RtsFlags.DebugFlags.weak = rtsTrue;
743                           break;
744                       case 'G':
745                           RtsFlags.DebugFlags.gccafs = rtsTrue;
746                           break;
747                       case 'g':
748                           RtsFlags.DebugFlags.gc = rtsTrue;
749                           break;
750                       case 'b':
751                           RtsFlags.DebugFlags.block_alloc = rtsTrue;
752                           break;
753                       case 'S':
754                           RtsFlags.DebugFlags.sanity = rtsTrue;
755                           break;
756                       case 't':
757                           RtsFlags.DebugFlags.stable = rtsTrue;
758                           break;
759                       case 'p':
760                           RtsFlags.DebugFlags.prof = rtsTrue;
761                           break;
762                       case 'r':
763                           RtsFlags.DebugFlags.gran = rtsTrue;
764                           break;
765                       case 'P':
766                           RtsFlags.DebugFlags.par = rtsTrue;
767                           break;
768                       case 'l':
769                           RtsFlags.DebugFlags.linker = rtsTrue;
770                           break;
771                       case 'a':
772                           RtsFlags.DebugFlags.apply = rtsTrue;
773                           break;
774                       case 'm':
775                           RtsFlags.DebugFlags.stm = rtsTrue;
776                           break;
777                       case 'z':
778                           RtsFlags.DebugFlags.squeeze = rtsTrue;
779                           break;
780                       case 'c':
781                           RtsFlags.DebugFlags.hpc = rtsTrue;
782                           break;
783                       default:
784                           bad_option( rts_argv[arg] );
785                       }
786                   }
787                   break;
788               }
789 #endif
790
791               case 'K':
792                 RtsFlags.GcFlags.maxStkSize = 
793                   decode(rts_argv[arg]+2) / sizeof(W_);
794
795                 if (RtsFlags.GcFlags.maxStkSize == 0) 
796                   bad_option( rts_argv[arg] );
797                 break;
798
799               case 'k':
800                 RtsFlags.GcFlags.initialStkSize = 
801                   decode(rts_argv[arg]+2) / sizeof(W_);
802
803                 if (RtsFlags.GcFlags.initialStkSize == 0) 
804                   bad_option( rts_argv[arg] );
805                 break;
806
807               case 'M':
808                 RtsFlags.GcFlags.maxHeapSize = 
809                   decode(rts_argv[arg]+2) / BLOCK_SIZE;
810                 /* user give size in *bytes* but "maxHeapSize" is in *blocks* */
811
812                 if (RtsFlags.GcFlags.maxHeapSize <= 0) {
813                   bad_option(rts_argv[arg]);
814                 }
815                 break;
816
817               case 'm':
818                 RtsFlags.GcFlags.pcFreeHeap = atof(rts_argv[arg]+2);
819
820                 if (RtsFlags.GcFlags.pcFreeHeap < 0 || 
821                     RtsFlags.GcFlags.pcFreeHeap > 100)
822                   bad_option( rts_argv[arg] );
823                 break;
824
825               case 'G':
826                 RtsFlags.GcFlags.generations = decode(rts_argv[arg]+2);
827                 if (RtsFlags.GcFlags.generations < 1) {
828                   bad_option(rts_argv[arg]);
829                 }
830                 break;
831
832               case 'T':
833                 RtsFlags.GcFlags.steps = decode(rts_argv[arg]+2);
834                 if (RtsFlags.GcFlags.steps < 1) {
835                   bad_option(rts_argv[arg]);
836                 }
837                 break;
838
839               case 'H':
840                 RtsFlags.GcFlags.heapSizeSuggestion = 
841                   decode(rts_argv[arg]+2) / BLOCK_SIZE;
842
843                 if (RtsFlags.GcFlags.heapSizeSuggestion <= 0) {
844                   bad_option(rts_argv[arg]);
845                 }
846                 break;
847
848 #ifdef RTS_GTK_FRONTPANEL
849               case 'f':
850                   RtsFlags.GcFlags.frontpanel = rtsTrue;
851                   break;
852 #endif
853
854               case 'I': /* idle GC delay */
855                 if (rts_argv[arg][2] == '\0') {
856                   /* use default */
857                 } else {
858                     I_ cst; /* tmp */
859
860                     /* Convert to millisecs */
861                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
862                     RtsFlags.GcFlags.idleGCDelayTime = cst;
863                 }
864                 break;
865
866               case 'S':
867                   RtsFlags.GcFlags.giveStats = VERBOSE_GC_STATS;
868                   goto stats;
869
870               case 's':
871                   RtsFlags.GcFlags.giveStats = SUMMARY_GC_STATS;
872                   goto stats;
873
874               case 't':
875                   RtsFlags.GcFlags.giveStats = ONELINE_GC_STATS;
876                   goto stats;
877
878             stats:
879 #ifdef PAR
880                 /* Opening all those files would almost certainly fail... */
881                 // RtsFlags.ParFlags.ParStats.Full = rtsTrue;
882                 RtsFlags.GcFlags.statsFile = NULL; /* temporary; ToDo: rm */
883 #else
884                 { 
885                     int r;
886                     r = open_stats_file(arg, *argc, argv,
887                                         *rts_argc, rts_argv, STAT_FILENAME_FMT,
888                                         &RtsFlags.GcFlags.statsFile);
889                     if (r == -1) { error = rtsTrue; }
890                 }
891 #endif
892                   break;
893
894               case 'Z':
895                 RtsFlags.GcFlags.squeezeUpdFrames = rtsFalse;
896                 break;
897
898               /* =========== PROFILING ========================== */
899
900               case 'P': /* detailed cost centre profiling (time/alloc) */
901               case 'p': /* cost centre profiling (time/alloc) */
902                 COST_CENTRE_USING_BUILD_ONLY(
903                 switch (rts_argv[arg][2]) {
904                   case 'x':
905                     RtsFlags.CcFlags.doCostCentres = COST_CENTRES_XML;
906                     break;
907                   case 'a':
908                     RtsFlags.CcFlags.doCostCentres = COST_CENTRES_ALL;
909                     break;
910                   default:
911                       if (rts_argv[arg][1] == 'P') {
912                           RtsFlags.CcFlags.doCostCentres =
913                               COST_CENTRES_VERBOSE;
914                       } else {
915                           RtsFlags.CcFlags.doCostCentres =
916                               COST_CENTRES_SUMMARY;
917                       }
918                       break;
919                 }
920                 ) break;
921
922               case 'R':
923                   PROFILING_BUILD_ONLY(
924                       RtsFlags.ProfFlags.maxRetainerSetSize = atof(rts_argv[arg]+2);
925                   ) break;
926               case 'L':
927                   PROFILING_BUILD_ONLY(
928                       RtsFlags.ProfFlags.ccsLength = atof(rts_argv[arg]+2);
929                       if(RtsFlags.ProfFlags.ccsLength <= 0) {
930                         bad_option(rts_argv[arg]);
931                       }
932                   ) break;
933               case 'h': /* serial heap profile */
934 #if !defined(PROFILING)
935                 switch (rts_argv[arg][2]) {
936                   case '\0':
937                   case 'T':
938                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CLOSURE_TYPE;
939                     break;
940                   default:
941                     errorBelch("invalid heap profile option: %s",rts_argv[arg]);
942                     error = rtsTrue;
943                 }
944 #else
945                 PROFILING_BUILD_ONLY(
946                 switch (rts_argv[arg][2]) {
947                 case '\0':
948                 case 'C':
949                 case 'c':
950                 case 'M':
951                 case 'm':
952                 case 'D':
953                 case 'd':
954                 case 'Y':
955                 case 'y':
956                 case 'R':
957                 case 'r':
958                 case 'B':
959                 case 'b':
960                     if (rts_argv[arg][2] != '\0' && rts_argv[arg][3] != '\0') {
961                         {
962                             char *left  = strchr(rts_argv[arg], '{');
963                             char *right = strrchr(rts_argv[arg], '}');
964
965                             // curly braces are optional, for
966                             // backwards compat.
967                             if (left)
968                                 left = left+1;
969                             else
970                                 left = rts_argv[arg] + 3;
971
972                             if (!right)
973                                 right = rts_argv[arg] + strlen(rts_argv[arg]);
974
975                             *right = '\0';
976
977                             switch (rts_argv[arg][2]) {
978                             case 'c': // cost centre label select
979                                 RtsFlags.ProfFlags.ccSelector = left;
980                                 break;
981                             case 'C':
982                                 RtsFlags.ProfFlags.ccsSelector = left;
983                                 break;
984                             case 'M':
985                             case 'm': // cost centre module select
986                                 RtsFlags.ProfFlags.modSelector = left;
987                                 break;
988                             case 'D':
989                             case 'd': // closure descr select 
990                                 RtsFlags.ProfFlags.descrSelector = left;
991                                 break;
992                             case 'Y':
993                             case 'y': // closure type select
994                                 RtsFlags.ProfFlags.typeSelector = left;
995                                 break;
996                             case 'R':
997                             case 'r': // retainer select
998                                 RtsFlags.ProfFlags.retainerSelector = left;
999                                 break;
1000                             case 'B':
1001                             case 'b': // biography select
1002                                 RtsFlags.ProfFlags.bioSelector = left;
1003                                 break;
1004                             }
1005                         }
1006                         break;
1007                     }
1008
1009                     if (RtsFlags.ProfFlags.doHeapProfile != 0) {
1010                         errorBelch("multiple heap profile options");
1011                         error = rtsTrue;
1012                         break;
1013                     }
1014
1015                     switch (rts_argv[arg][2]) {
1016                     case '\0':
1017                     case 'C':
1018                     case 'c':
1019                         RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CCS;
1020                         break;
1021                     case 'M':
1022                     case 'm':
1023                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_MOD;
1024                           break;
1025                     case 'D':
1026                     case 'd':
1027                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_DESCR;
1028                           break;
1029                     case 'Y':
1030                     case 'y':
1031                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_TYPE;
1032                           break;
1033                     case 'R':
1034                     case 'r':
1035                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_RETAINER;
1036                           break;
1037                     case 'B':
1038                     case 'b':
1039                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_LDV;
1040                           break;
1041                     }
1042                     break;
1043                       
1044                 default:
1045                     errorBelch("invalid heap profile option: %s",rts_argv[arg]);
1046                     error = rtsTrue;
1047                 }
1048                 ) 
1049 #endif /* PROFILING */
1050                 break;
1051
1052               case 'i': /* heap sample interval */
1053                 if (rts_argv[arg][2] == '\0') {
1054                   /* use default */
1055                 } else {
1056                     I_ cst; /* tmp */
1057
1058                     /* Convert to milliseconds */
1059                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
1060                     RtsFlags.ProfFlags.profileInterval = cst;
1061                 }
1062                 break;
1063
1064               /* =========== CONCURRENT ========================= */
1065               case 'C': /* context switch interval */
1066                 if (rts_argv[arg][2] == '\0')
1067                     RtsFlags.ConcFlags.ctxtSwitchTime = 0;
1068                 else {
1069                     I_ cst; /* tmp */
1070
1071                     /* Convert to milliseconds */
1072                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
1073                     RtsFlags.ConcFlags.ctxtSwitchTime = cst;
1074                 }
1075                 break;
1076
1077               case 'V': /* master tick interval */
1078                 if (rts_argv[arg][2] == '\0') {
1079                     // turns off ticks completely
1080                     RtsFlags.MiscFlags.tickInterval = 0;
1081                 } else {
1082                     I_ cst; /* tmp */
1083
1084                     /* Convert to milliseconds */
1085                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
1086                     RtsFlags.MiscFlags.tickInterval = cst;
1087                 }
1088                 break;
1089
1090 #if defined(THREADED_RTS) && !defined(NOSMP)
1091               case 'N':
1092                 THREADED_BUILD_ONLY(
1093                 if (rts_argv[arg][2] != '\0') {
1094                     RtsFlags.ParFlags.nNodes
1095                       = strtol(rts_argv[arg]+2, (char **) NULL, 10);
1096                     if (RtsFlags.ParFlags.nNodes <= 0) {
1097                       errorBelch("bad value for -N");
1098                       error = rtsTrue;
1099                     }
1100                 }
1101                 ) break;
1102
1103               case 'q':
1104                     switch (rts_argv[arg][2]) {
1105                     case '\0':
1106                         errorBelch("incomplete RTS option: %s",rts_argv[arg]);
1107                         error = rtsTrue;
1108                         break;
1109                     case 'm':
1110                         RtsFlags.ParFlags.migrate = rtsFalse;
1111                         break;
1112                     case 'w':
1113                         RtsFlags.ParFlags.wakeupMigrate = rtsTrue;
1114                         break;
1115                     default:
1116                         errorBelch("unknown RTS option: %s",rts_argv[arg]);
1117                         error = rtsTrue;
1118                         break;
1119                     }
1120                     break;
1121 #endif
1122               /* =========== PARALLEL =========================== */
1123               case 'e':
1124                 PAR_OR_THREADED_BUILD_ONLY(
1125                 if (rts_argv[arg][2] != '\0') {
1126                     RtsFlags.ParFlags.maxLocalSparks
1127                       = strtol(rts_argv[arg]+2, (char **) NULL, 10);
1128                     if (RtsFlags.ParFlags.maxLocalSparks <= 0) {
1129                       errorBelch("bad value for -e");
1130                       error = rtsTrue;
1131                     }
1132                 }
1133                 ) break;
1134
1135 #ifdef PAR
1136               case 'q':
1137                 PAR_BUILD_ONLY(
1138                   process_par_option(arg, rts_argc, rts_argv, &error);
1139                 ) break;
1140 #endif
1141
1142               /* =========== GRAN =============================== */
1143
1144               case 'b':
1145                 GRAN_BUILD_ONLY(
1146                   process_gran_option(arg, rts_argc, rts_argv, &error);
1147                 ) break;
1148
1149               /* =========== TICKY ============================== */
1150
1151               case 'r': /* Basic profiling stats */
1152                 TICKY_BUILD_ONLY(
1153
1154                 RtsFlags.TickyFlags.showTickyStats = rtsTrue;
1155
1156                 { 
1157                     int r;
1158                     r = open_stats_file(arg, *argc, argv,
1159                                         *rts_argc, rts_argv, TICKY_FILENAME_FMT,
1160                                         &RtsFlags.TickyFlags.tickyFile);
1161                     if (r == -1) { error = rtsTrue; }
1162                 }
1163                 ) break;
1164
1165               /* =========== TRACING ---------=================== */
1166
1167               case 'v':
1168                 switch(rts_argv[arg][2]) {
1169                 case '\0':
1170                     errorBelch("incomplete RTS option: %s",rts_argv[arg]);
1171                     error = rtsTrue;
1172                     break;
1173                 case 't':
1174                     RtsFlags.TraceFlags.timestamp = rtsTrue;
1175                     break;
1176                 case 's':
1177                     RtsFlags.TraceFlags.sched = rtsTrue;
1178                     break;
1179                 default:
1180                     errorBelch("unknown RTS option: %s",rts_argv[arg]);
1181                     error = rtsTrue;
1182                     break;
1183                 }
1184                 break;
1185
1186               /* =========== EXTENDED OPTIONS =================== */
1187
1188               case 'x': /* Extend the argument space */
1189                 switch(rts_argv[arg][2]) {
1190                   case '\0':
1191                     errorBelch("incomplete RTS option: %s",rts_argv[arg]);
1192                     error = rtsTrue;
1193                     break;
1194
1195                   case 'c': /* Debugging tool: show current cost centre on an exception */
1196                     PROFILING_BUILD_ONLY(
1197                         RtsFlags.ProfFlags.showCCSOnException = rtsTrue;
1198                         );
1199                     break;
1200
1201                 case 't':  /* Include memory used by TSOs in a heap profile */
1202                     PROFILING_BUILD_ONLY(
1203                         RtsFlags.ProfFlags.includeTSOs = rtsTrue;
1204                         );
1205                     break;
1206
1207                   /* The option prefix '-xx' is reserved for future extension.  KSW 1999-11. */
1208
1209                   default:
1210                     errorBelch("unknown RTS option: %s",rts_argv[arg]);
1211                     error = rtsTrue;
1212                     break;
1213                 }
1214                 break;  /* defensive programming */
1215
1216               /* =========== OH DEAR ============================ */
1217               default:
1218                 errorBelch("unknown RTS option: %s",rts_argv[arg]);
1219                 error = rtsTrue;
1220                 break;
1221             }
1222         }
1223     }
1224
1225     // Determine what tick interval we should use for the RTS timer
1226     // by taking the shortest of the various intervals that we need to
1227     // monitor.
1228     if (RtsFlags.MiscFlags.tickInterval <= 0) {
1229         RtsFlags.MiscFlags.tickInterval = 50;
1230     }
1231
1232     if (RtsFlags.ConcFlags.ctxtSwitchTime > 0) {
1233         RtsFlags.MiscFlags.tickInterval =
1234             stg_min(RtsFlags.ConcFlags.ctxtSwitchTime,
1235                     RtsFlags.MiscFlags.tickInterval);
1236     }
1237
1238     if (RtsFlags.GcFlags.idleGCDelayTime > 0) {
1239         RtsFlags.MiscFlags.tickInterval =
1240             stg_min(RtsFlags.GcFlags.idleGCDelayTime,
1241                     RtsFlags.MiscFlags.tickInterval);
1242     }
1243
1244     if (RtsFlags.ProfFlags.profileInterval > 0) {
1245         RtsFlags.MiscFlags.tickInterval =
1246             stg_min(RtsFlags.ProfFlags.profileInterval,
1247                     RtsFlags.MiscFlags.tickInterval);
1248     }
1249
1250     if (RtsFlags.ConcFlags.ctxtSwitchTime > 0) {
1251         RtsFlags.ConcFlags.ctxtSwitchTicks =
1252             RtsFlags.ConcFlags.ctxtSwitchTime /
1253             RtsFlags.MiscFlags.tickInterval;
1254     } else {
1255         RtsFlags.ConcFlags.ctxtSwitchTicks = 0;
1256     }
1257
1258     RtsFlags.ProfFlags.profileIntervalTicks =
1259         RtsFlags.ProfFlags.profileInterval / RtsFlags.MiscFlags.tickInterval;
1260
1261     if (error) {
1262         const char **p;
1263
1264         fflush(stdout);
1265         for (p = usage_text; *p; p++)
1266             errorBelch("%s", *p);
1267         stg_exit(EXIT_FAILURE);
1268     }
1269 }
1270
1271 #if defined(GRAN)
1272
1273 static void
1274 enable_GranSimLight(void) {
1275
1276     debugBelch("GrAnSim Light enabled (infinite number of processors;  0 communication costs)\n");
1277     RtsFlags.GranFlags.Light=rtsTrue;
1278     RtsFlags.GranFlags.Costs.latency = 
1279         RtsFlags.GranFlags.Costs.fetchtime = 
1280         RtsFlags.GranFlags.Costs.additional_latency =
1281         RtsFlags.GranFlags.Costs.gunblocktime = 
1282         RtsFlags.GranFlags.Costs.lunblocktime =
1283         RtsFlags.GranFlags.Costs.threadcreatetime = 
1284         RtsFlags.GranFlags.Costs.threadqueuetime =
1285         RtsFlags.GranFlags.Costs.threadscheduletime = 
1286         RtsFlags.GranFlags.Costs.threaddescheduletime =
1287         RtsFlags.GranFlags.Costs.threadcontextswitchtime = 0;
1288   
1289     RtsFlags.GranFlags.Costs.mpacktime = 
1290         RtsFlags.GranFlags.Costs.munpacktime = 0;
1291
1292     RtsFlags.GranFlags.DoFairSchedule = rtsTrue;
1293     RtsFlags.GranFlags.DoAsyncFetch = rtsFalse;
1294     RtsFlags.GranFlags.DoAlwaysCreateThreads = rtsTrue;
1295     /* FetchStrategy is irrelevant in GrAnSim-Light */
1296
1297     /* GrAnSim Light often creates an abundance of parallel threads,
1298        each with its own stack etc. Therefore, it's in general a good
1299        idea to use small stack chunks (use the -o<size> option to 
1300        increase it again). 
1301     */
1302     // RtsFlags.ConcFlags.stkChunkSize = 100;
1303
1304     RtsFlags.GranFlags.proc = 1; 
1305 }
1306
1307 static void
1308 process_gran_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
1309 {
1310     if (rts_argv[arg][1] != 'b') /* All GranSim options start with -b */
1311       return;
1312
1313     /* or a ridiculously idealised simulator */
1314     if(strcmp((rts_argv[arg]+2),"oring")==0) {
1315       RtsFlags.GranFlags.Costs.latency = 
1316         RtsFlags.GranFlags.Costs.fetchtime = 
1317         RtsFlags.GranFlags.Costs.additional_latency =
1318         RtsFlags.GranFlags.Costs.gunblocktime = 
1319         RtsFlags.GranFlags.Costs.lunblocktime =
1320         RtsFlags.GranFlags.Costs.threadcreatetime = 
1321         RtsFlags.GranFlags.Costs.threadqueuetime =
1322         RtsFlags.GranFlags.Costs.threadscheduletime = 
1323         RtsFlags.GranFlags.Costs.threaddescheduletime =
1324         RtsFlags.GranFlags.Costs.threadcontextswitchtime = 0;
1325
1326       RtsFlags.GranFlags.Costs.mpacktime = 
1327         RtsFlags.GranFlags.Costs.munpacktime = 0;
1328
1329       RtsFlags.GranFlags.Costs.arith_cost = 
1330         RtsFlags.GranFlags.Costs.float_cost = 
1331         RtsFlags.GranFlags.Costs.load_cost =
1332         RtsFlags.GranFlags.Costs.store_cost = 
1333         RtsFlags.GranFlags.Costs.branch_cost = 0;
1334
1335       RtsFlags.GranFlags.Costs.heapalloc_cost = 1;
1336
1337       /* ++RtsFlags.GranFlags.DoFairSchedule; */
1338       RtsFlags.GranFlags.DoStealThreadsFirst = rtsTrue;        /* -bZ */
1339       RtsFlags.GranFlags.DoThreadMigration   = rtsTrue;        /* -bM */
1340       RtsFlags.GranFlags.GranSimStats.Full   = rtsTrue;        /* -bP */
1341       return;
1342     }
1343
1344       /* or a somewhat idealised simulator */
1345       if(strcmp((rts_argv[arg]+2),"onzo")==0) {
1346         RtsFlags.GranFlags.Costs.latency = 
1347         RtsFlags.GranFlags.Costs.fetchtime = 
1348         RtsFlags.GranFlags.Costs.additional_latency =
1349         RtsFlags.GranFlags.Costs.gunblocktime = 
1350         RtsFlags.GranFlags.Costs.lunblocktime =
1351         RtsFlags.GranFlags.Costs.threadcreatetime = 
1352         RtsFlags.GranFlags.Costs.threadqueuetime =
1353         RtsFlags.GranFlags.Costs.threadscheduletime = 
1354         RtsFlags.GranFlags.Costs.threaddescheduletime =
1355         RtsFlags.GranFlags.Costs.threadcontextswitchtime = 0;
1356
1357         RtsFlags.GranFlags.Costs.mpacktime = 
1358         RtsFlags.GranFlags.Costs.munpacktime = 0;
1359         
1360         RtsFlags.GranFlags.Costs.heapalloc_cost = 1;
1361
1362         /* RtsFlags.GranFlags.DoFairSchedule  = rtsTrue; */       /* -b-R */
1363         /* RtsFlags.GranFlags.DoStealThreadsFirst = rtsTrue; */   /* -b-T */
1364         RtsFlags.GranFlags.DoAsyncFetch = rtsTrue;         /* -bZ */
1365         RtsFlags.GranFlags.DoThreadMigration  = rtsTrue;          /* -bM */
1366         RtsFlags.GranFlags.GranSimStats.Full  = rtsTrue;          /* -bP */
1367 #  if defined(GRAN_CHECK) && defined(GRAN)
1368         RtsFlags.GranFlags.Debug.event_stats = rtsTrue; /* print event statistics   */
1369 #  endif
1370         return;
1371       }
1372
1373       /* Communication and task creation cost parameters */
1374       switch(rts_argv[arg][2]) {
1375         case '.':
1376           IgnoreYields = rtsTrue; // HWL HACK
1377           break;
1378
1379         case ':':
1380           enable_GranSimLight();       /* set flags for GrAnSim-Light mode */
1381           break;
1382
1383         case 'l':
1384           if (rts_argv[arg][3] != '\0')
1385             {
1386               RtsFlags.GranFlags.Costs.gunblocktime = 
1387               RtsFlags.GranFlags.Costs.latency = decode(rts_argv[arg]+3);
1388               RtsFlags.GranFlags.Costs.fetchtime = 2*RtsFlags.GranFlags.Costs.latency;
1389             }
1390           else
1391             RtsFlags.GranFlags.Costs.latency = LATENCY;
1392           break;
1393
1394         case 'a':
1395           if (rts_argv[arg][3] != '\0')
1396             RtsFlags.GranFlags.Costs.additional_latency = decode(rts_argv[arg]+3);
1397           else
1398             RtsFlags.GranFlags.Costs.additional_latency = ADDITIONAL_LATENCY;
1399           break;
1400
1401         case 'm':
1402           if (rts_argv[arg][3] != '\0')
1403             RtsFlags.GranFlags.Costs.mpacktime = decode(rts_argv[arg]+3);
1404           else
1405             RtsFlags.GranFlags.Costs.mpacktime = MSGPACKTIME;
1406           break;
1407
1408         case 'x':
1409           if (rts_argv[arg][3] != '\0')
1410             RtsFlags.GranFlags.Costs.mtidytime = decode(rts_argv[arg]+3);
1411           else
1412             RtsFlags.GranFlags.Costs.mtidytime = 0;
1413           break;
1414
1415         case 'r':
1416           if (rts_argv[arg][3] != '\0')
1417             RtsFlags.GranFlags.Costs.munpacktime = decode(rts_argv[arg]+3);
1418           else
1419             RtsFlags.GranFlags.Costs.munpacktime = MSGUNPACKTIME;
1420           break;
1421           
1422         case 'g':
1423           if (rts_argv[arg][3] != '\0')
1424             RtsFlags.GranFlags.Costs.fetchtime = decode(rts_argv[arg]+3);
1425           else
1426             RtsFlags.GranFlags.Costs.fetchtime = FETCHTIME;
1427           break;
1428           
1429         case 'n':
1430           if (rts_argv[arg][3] != '\0')
1431             RtsFlags.GranFlags.Costs.gunblocktime = decode(rts_argv[arg]+3);
1432           else
1433             RtsFlags.GranFlags.Costs.gunblocktime = GLOBALUNBLOCKTIME;
1434           break;
1435
1436         case 'u':
1437           if (rts_argv[arg][3] != '\0')
1438             RtsFlags.GranFlags.Costs.lunblocktime = decode(rts_argv[arg]+3);
1439           else
1440             RtsFlags.GranFlags.Costs.lunblocktime = LOCALUNBLOCKTIME;
1441           break;
1442
1443         /* Thread-related metrics */
1444         case 't':
1445           if (rts_argv[arg][3] != '\0')
1446             RtsFlags.GranFlags.Costs.threadcreatetime = decode(rts_argv[arg]+3);
1447           else
1448             RtsFlags.GranFlags.Costs.threadcreatetime = THREADCREATETIME;
1449           break;
1450           
1451         case 'q':
1452           if (rts_argv[arg][3] != '\0')
1453             RtsFlags.GranFlags.Costs.threadqueuetime = decode(rts_argv[arg]+3);
1454           else
1455             RtsFlags.GranFlags.Costs.threadqueuetime = THREADQUEUETIME;
1456           break;
1457           
1458         case 'c':
1459           if (rts_argv[arg][3] != '\0')
1460             RtsFlags.GranFlags.Costs.threadscheduletime = decode(rts_argv[arg]+3);
1461           else
1462             RtsFlags.GranFlags.Costs.threadscheduletime = THREADSCHEDULETIME;
1463           
1464           RtsFlags.GranFlags.Costs.threadcontextswitchtime = RtsFlags.GranFlags.Costs.threadscheduletime
1465             + RtsFlags.GranFlags.Costs.threaddescheduletime;
1466           break;
1467
1468         case 'd':
1469           if (rts_argv[arg][3] != '\0')
1470             RtsFlags.GranFlags.Costs.threaddescheduletime = decode(rts_argv[arg]+3);
1471           else
1472             RtsFlags.GranFlags.Costs.threaddescheduletime = THREADDESCHEDULETIME;
1473           
1474           RtsFlags.GranFlags.Costs.threadcontextswitchtime = RtsFlags.GranFlags.Costs.threadscheduletime
1475             + RtsFlags.GranFlags.Costs.threaddescheduletime;
1476           break;
1477
1478         /* Instruction Cost Metrics */
1479         case 'A':
1480           if (rts_argv[arg][3] != '\0')
1481             RtsFlags.GranFlags.Costs.arith_cost = decode(rts_argv[arg]+3);
1482           else
1483             RtsFlags.GranFlags.Costs.arith_cost = ARITH_COST;
1484           break;
1485
1486         case 'F':
1487           if (rts_argv[arg][3] != '\0')
1488             RtsFlags.GranFlags.Costs.float_cost = decode(rts_argv[arg]+3);
1489           else
1490             RtsFlags.GranFlags.Costs.float_cost = FLOAT_COST;
1491           break;
1492                       
1493         case 'B':
1494           if (rts_argv[arg][3] != '\0')
1495             RtsFlags.GranFlags.Costs.branch_cost = decode(rts_argv[arg]+3);
1496           else
1497             RtsFlags.GranFlags.Costs.branch_cost = BRANCH_COST;
1498           break;
1499
1500         case 'L':
1501           if (rts_argv[arg][3] != '\0')
1502             RtsFlags.GranFlags.Costs.load_cost = decode(rts_argv[arg]+3);
1503           else
1504             RtsFlags.GranFlags.Costs.load_cost = LOAD_COST;
1505           break;
1506           
1507         case 'S':
1508           if (rts_argv[arg][3] != '\0')
1509             RtsFlags.GranFlags.Costs.store_cost = decode(rts_argv[arg]+3);
1510           else
1511             RtsFlags.GranFlags.Costs.store_cost = STORE_COST;
1512           break;
1513
1514         case 'H':
1515           if (rts_argv[arg][3] != '\0')
1516             RtsFlags.GranFlags.Costs.heapalloc_cost = decode(rts_argv[arg]+3);
1517           else
1518             RtsFlags.GranFlags.Costs.heapalloc_cost = 0;
1519           break;
1520
1521         case 'y':
1522           RtsFlags.GranFlags.DoAsyncFetch = rtsTrue;
1523           if (rts_argv[arg][3] != '\0')
1524             RtsFlags.GranFlags.FetchStrategy = decode(rts_argv[arg]+3);
1525           else
1526             RtsFlags.GranFlags.FetchStrategy = 2;
1527           if (RtsFlags.GranFlags.FetchStrategy == 0)
1528             RtsFlags.GranFlags.DoAsyncFetch = rtsFalse;
1529           break;
1530           
1531         case 'K':   /* sort overhead (per elem in spark list) */
1532           if (rts_argv[arg][3] != '\0')
1533             RtsFlags.GranFlags.Costs.pri_spark_overhead = decode(rts_argv[arg]+3);
1534           else
1535             RtsFlags.GranFlags.Costs.pri_spark_overhead = PRI_SPARK_OVERHEAD;
1536           debugBelch("Overhead for pri spark: %d (per elem).\n",
1537                          RtsFlags.GranFlags.Costs.pri_spark_overhead);
1538           break;
1539
1540         case 'O':  /* sort overhead (per elem in spark list) */
1541           if (rts_argv[arg][3] != '\0')
1542             RtsFlags.GranFlags.Costs.pri_sched_overhead = decode(rts_argv[arg]+3);
1543           else
1544             RtsFlags.GranFlags.Costs.pri_sched_overhead = PRI_SCHED_OVERHEAD;
1545           debugBelch("Overhead for pri sched: %d (per elem).\n",
1546                        RtsFlags.GranFlags.Costs.pri_sched_overhead);
1547           break;
1548
1549         /* General Parameters */
1550         case 'p':
1551           if (rts_argv[arg][3] != '\0')
1552             {
1553               RtsFlags.GranFlags.proc = decode(rts_argv[arg]+3);
1554               if (RtsFlags.GranFlags.proc==0) {
1555                   enable_GranSimLight(); /* set flags for GrAnSim-Light mode */
1556               } else if (RtsFlags.GranFlags.proc > MAX_PROC || 
1557                          RtsFlags.GranFlags.proc < 1)
1558                 {
1559                   debugBelch("setupRtsFlags: no more than %u processors allowed\n",
1560                           MAX_PROC);
1561                   *error = rtsTrue;
1562                 }
1563             }
1564           else
1565             RtsFlags.GranFlags.proc = MAX_PROC;
1566           break;
1567
1568         case 'f':
1569           RtsFlags.GranFlags.Fishing = rtsTrue;
1570           if (rts_argv[arg][3] != '\0')
1571             RtsFlags.GranFlags.maxFishes = decode(rts_argv[arg]+3);
1572           else
1573             RtsFlags.GranFlags.maxFishes = MAX_FISHES;
1574           break;
1575           
1576         case 'w':
1577           if (rts_argv[arg][3] != '\0')
1578             RtsFlags.GranFlags.time_slice = decode(rts_argv[arg]+3);
1579           else
1580             RtsFlags.GranFlags.time_slice = GRAN_TIME_SLICE;
1581           break;
1582           
1583         case 'C':
1584           RtsFlags.GranFlags.DoAlwaysCreateThreads=rtsTrue;
1585           RtsFlags.GranFlags.DoThreadMigration=rtsTrue;
1586           break;
1587
1588         case 'G':
1589           debugBelch("Bulk fetching enabled.\n");
1590           RtsFlags.GranFlags.DoBulkFetching=rtsTrue;
1591           break;
1592           
1593         case 'M':
1594           debugBelch("Thread migration enabled.\n");
1595           RtsFlags.GranFlags.DoThreadMigration=rtsTrue;
1596           break;
1597
1598         case 'R':
1599           debugBelch("Fair Scheduling enabled.\n");
1600           RtsFlags.GranFlags.DoFairSchedule=rtsTrue;
1601           break;
1602           
1603         case 'I':
1604           debugBelch("Priority Scheduling enabled.\n");
1605           RtsFlags.GranFlags.DoPriorityScheduling=rtsTrue;
1606           break;
1607
1608         case 'T':
1609           RtsFlags.GranFlags.DoStealThreadsFirst=rtsTrue;
1610           RtsFlags.GranFlags.DoThreadMigration=rtsTrue;
1611           break;
1612           
1613         case 'Z':
1614           RtsFlags.GranFlags.DoAsyncFetch=rtsTrue;
1615           break;
1616           
1617 /*          case 'z': */
1618 /*        RtsFlags.GranFlags.SimplifiedFetch=rtsTrue; */
1619 /*        break; */
1620           
1621         case 'N':
1622           RtsFlags.GranFlags.PreferSparksOfLocalNodes=rtsTrue;
1623           break;
1624           
1625         case 'b':
1626           RtsFlags.GranFlags.GranSimStats.Binary=rtsTrue;
1627           break;
1628           
1629         case 'P':
1630           /* format is -bP<c> where <c> is one char describing kind of profile */
1631           RtsFlags.GranFlags.GranSimStats.Full = rtsTrue;
1632           switch(rts_argv[arg][3]) {
1633           case '\0': break; // nothing special, just an ordinary profile
1634           case '0': RtsFlags.GranFlags.GranSimStats.Suppressed = rtsTrue;
1635             break;
1636           case 'b': RtsFlags.GranFlags.GranSimStats.Binary = rtsTrue;
1637             break;
1638           case 's': RtsFlags.GranFlags.GranSimStats.Sparks = rtsTrue;
1639             break;
1640           case 'h': RtsFlags.GranFlags.GranSimStats.Heap = rtsTrue;
1641             break;
1642           case 'n': RtsFlags.GranFlags.GranSimStats.NewLogfile = rtsTrue;
1643             break;
1644           case 'g': RtsFlags.GranFlags.GranSimStats.Global = rtsTrue;
1645             break;
1646           default: barf("Unknown option -bP%c", rts_argv[arg][3]);
1647           }
1648           break;
1649
1650         case 's':
1651           RtsFlags.GranFlags.GranSimStats.Sparks=rtsTrue;
1652           break;
1653
1654         case 'h':
1655           RtsFlags.GranFlags.GranSimStats.Heap=rtsTrue;
1656           break;
1657
1658         case 'Y':   /* syntax: -bY<n>[,<n>]  n ... pos int */ 
1659           if (rts_argv[arg][3] != '\0') {
1660             char *arg0, *tmp;
1661             
1662             arg0 = rts_argv[arg]+3;
1663             if ((tmp = strstr(arg0,","))==NULL) {
1664               RtsFlags.GranFlags.SparkPriority = decode(arg0);
1665               debugBelch("SparkPriority: %u.\n",RtsFlags.GranFlags.SparkPriority);
1666             } else {
1667               *(tmp++) = '\0'; 
1668               RtsFlags.GranFlags.SparkPriority = decode(arg0);
1669               RtsFlags.GranFlags.SparkPriority2 = decode(tmp);
1670               debugBelch("SparkPriority: %u.\n",
1671                       RtsFlags.GranFlags.SparkPriority);
1672               debugBelch("SparkPriority2:%u.\n",
1673                       RtsFlags.GranFlags.SparkPriority2);
1674               if (RtsFlags.GranFlags.SparkPriority2 < 
1675                   RtsFlags.GranFlags.SparkPriority) {
1676                 debugBelch("WARNING: 2nd pri < main pri (%u<%u); 2nd pri has no effect\n",
1677                         RtsFlags.GranFlags.SparkPriority2,
1678                         RtsFlags.GranFlags.SparkPriority);
1679               }
1680             }
1681           } else {
1682             /* plain pri spark is now invoked with -bX  
1683                RtsFlags.GranFlags.DoPrioritySparking = 1;
1684                debugBelch("PrioritySparking.\n");
1685             */
1686           }
1687           break;
1688
1689         case 'Q':
1690           if (rts_argv[arg][3] != '\0') {
1691             RtsFlags.GranFlags.ThunksToPack = decode(rts_argv[arg]+3);
1692           } else {
1693             RtsFlags.GranFlags.ThunksToPack = 1;
1694           }
1695           debugBelch("Thunks To Pack in one packet: %u.\n",
1696                   RtsFlags.GranFlags.ThunksToPack);
1697           break;
1698                       
1699         case 'e':
1700           RtsFlags.GranFlags.RandomSteal = rtsFalse;
1701           debugBelch("Deterministic mode (no random stealing)\n");
1702                       break;
1703
1704           /* The following class of options contains eXperimental */
1705           /* features in connection with exploiting granularity */
1706           /* information. I.e. if -bY is chosen these options */
1707           /* tell the RTS what to do with the supplied info --HWL */
1708
1709         case 'W':
1710           if (rts_argv[arg][3] != '\0') {
1711             RtsFlags.GranFlags.packBufferSize_internal = decode(rts_argv[arg]+3);
1712           } else {
1713             RtsFlags.GranFlags.packBufferSize_internal = GRANSIM_DEFAULT_PACK_BUFFER_SIZE;
1714           }
1715           debugBelch("Size of GranSim internal pack buffer: %u.\n",
1716                   RtsFlags.GranFlags.packBufferSize_internal);
1717           break;
1718                       
1719         case 'X':
1720           switch(rts_argv[arg][3]) {
1721             
1722             case '\0':
1723               RtsFlags.GranFlags.DoPrioritySparking = 1;
1724               debugBelch("Priority Sparking with Normal Priorities.\n");
1725               RtsFlags.GranFlags.InversePriorities = rtsFalse; 
1726               RtsFlags.GranFlags.RandomPriorities = rtsFalse;
1727               RtsFlags.GranFlags.IgnorePriorities = rtsFalse;
1728               break;
1729                         
1730             case 'I':
1731               RtsFlags.GranFlags.DoPrioritySparking = 1;
1732               debugBelch("Priority Sparking with Inverse Priorities.\n");
1733               RtsFlags.GranFlags.InversePriorities++; 
1734               break;
1735               
1736             case 'R': 
1737               RtsFlags.GranFlags.DoPrioritySparking = 1;
1738               debugBelch("Priority Sparking with Random Priorities.\n");
1739               RtsFlags.GranFlags.RandomPriorities++;
1740               break;
1741               
1742             case 'N':
1743               RtsFlags.GranFlags.DoPrioritySparking = 1;
1744               debugBelch("Priority Sparking with No Priorities.\n");
1745               RtsFlags.GranFlags.IgnorePriorities++;
1746               break;
1747               
1748             default:
1749               bad_option( rts_argv[arg] );
1750               break;
1751           }
1752           break;
1753
1754         case '-':
1755           switch(rts_argv[arg][3]) {
1756             
1757             case 'C':
1758               RtsFlags.GranFlags.DoAlwaysCreateThreads=rtsFalse;
1759               RtsFlags.GranFlags.DoThreadMigration=rtsFalse;
1760               break;
1761
1762             case 'G':
1763               RtsFlags.GranFlags.DoBulkFetching=rtsFalse;
1764               break;
1765               
1766             case 'M':
1767               RtsFlags.GranFlags.DoThreadMigration=rtsFalse;
1768               break;
1769
1770             case 'R':
1771               RtsFlags.GranFlags.DoFairSchedule=rtsFalse;
1772               break;
1773
1774             case 'T':
1775               RtsFlags.GranFlags.DoStealThreadsFirst=rtsFalse;
1776               RtsFlags.GranFlags.DoThreadMigration=rtsFalse;
1777               break;
1778
1779             case 'Z':
1780               RtsFlags.GranFlags.DoAsyncFetch=rtsFalse;
1781               break;
1782               
1783             case 'N':
1784               RtsFlags.GranFlags.PreferSparksOfLocalNodes=rtsFalse;
1785                          break;
1786                          
1787             case 'P':
1788               RtsFlags.GranFlags.GranSimStats.Suppressed=rtsTrue;
1789               break;
1790
1791             case 's':
1792               RtsFlags.GranFlags.GranSimStats.Sparks=rtsFalse;
1793               break;
1794             
1795             case 'h':
1796               RtsFlags.GranFlags.GranSimStats.Heap=rtsFalse;
1797               break;
1798             
1799             case 'b':
1800               RtsFlags.GranFlags.GranSimStats.Binary=rtsFalse;
1801               break;
1802                          
1803             case 'X':
1804               RtsFlags.GranFlags.DoPrioritySparking = rtsFalse;
1805               break;
1806
1807             case 'Y':
1808               RtsFlags.GranFlags.DoPrioritySparking = rtsFalse;
1809               RtsFlags.GranFlags.SparkPriority = rtsFalse;
1810               break;
1811
1812             case 'I':
1813               RtsFlags.GranFlags.DoPriorityScheduling = rtsFalse;
1814               break;
1815
1816             case 'e':
1817               RtsFlags.GranFlags.RandomSteal = rtsFalse;
1818               break;
1819
1820             default:
1821               bad_option( rts_argv[arg] );
1822               break;
1823           }
1824           break;
1825
1826 #  if defined(GRAN_CHECK) && defined(GRAN)
1827         case 'D':
1828           switch(rts_argv[arg][3]) {
1829             case 'Q':    /* Set pack buffer size (same as 'Q' in GUM) */
1830               if (rts_argv[arg][4] != '\0') {
1831                 RtsFlags.GranFlags.packBufferSize = decode(rts_argv[arg]+4);
1832                 debugBelch("Pack buffer size: %d\n",
1833                         RtsFlags.GranFlags.packBufferSize);
1834               } else {
1835                 debugBelch("setupRtsFlags: missing size of PackBuffer (for -Q)\n");
1836                 *error = rtsTrue;
1837               }
1838               break;
1839
1840           default:
1841               if (isdigit(rts_argv[arg][3])) {/* Set all debugging options in one */
1842                 /* hack warning: interpret the flags as a binary number */
1843                 nat n = decode(rts_argv[arg]+3);
1844                 set_GranSim_debug_options(n);
1845               } else {
1846                 nat i;
1847                 for (i=0; i<=MAX_GRAN_DEBUG_OPTION; i++) 
1848                   if (rts_argv[arg][3] == gran_debug_opts_flags[i])
1849                     break;
1850                 
1851                 if (i==MAX_GRAN_DEBUG_OPTION+1) {
1852                   debugBelch("Valid GranSim debug options are:\n");
1853                   help_GranSim_debug_options(MAX_GRAN_DEBUG_MASK);
1854                   bad_option( rts_argv[arg] );
1855                 } else { // flag found; now set it
1856                   set_GranSim_debug_options(GRAN_DEBUG_MASK(i));  // 2^i
1857                 }
1858               }
1859               break;
1860               
1861 #if 0
1862             case 'e':       /* event trace; also -bD1 */
1863               debugBelch("DEBUG: event_trace; printing event trace.\n");
1864               RtsFlags.GranFlags.Debug.event_trace = rtsTrue;
1865               /* RtsFlags.GranFlags.event_trace=rtsTrue; */
1866               break;
1867               
1868             case 'E':       /* event statistics; also -bD2 */
1869               debugBelch("DEBUG: event_stats; printing event statistics.\n");
1870               RtsFlags.GranFlags.Debug.event_stats = rtsTrue;
1871               /* RtsFlags.GranFlags.Debug |= 0x20; print event statistics   */
1872               break;
1873               
1874             case 'f':       /* thunkStealing; also -bD4 */
1875               debugBelch("DEBUG: thunkStealing; printing forwarding of FETCHNODES.\n");
1876               RtsFlags.GranFlags.Debug.thunkStealing = rtsTrue;
1877               /* RtsFlags.GranFlags.Debug |= 0x2;  print fwd messages */
1878               break;
1879
1880             case 'z':       /* blockOnFetch; also -bD8 */
1881               debugBelch("DEBUG: blockOnFetch; check for blocked on fetch.\n");
1882               RtsFlags.GranFlags.Debug.blockOnFetch = rtsTrue;
1883               /* RtsFlags.GranFlags.Debug |= 0x4; debug non-reschedule-on-fetch */
1884               break;
1885               
1886             case 't':       /* blockOnFetch_sanity; also -bD16 */  
1887               debugBelch("DEBUG: blockOnFetch_sanity; check for TSO asleep on fetch.\n");
1888               RtsFlags.GranFlags.Debug.blockOnFetch_sanity = rtsTrue;
1889               /* RtsFlags.GranFlags.Debug |= 0x10; debug TSO asleep for fetch  */
1890               break;
1891
1892             case 'S':       /* priSpark; also -bD32 */
1893               debugBelch("DEBUG: priSpark; priority sparking.\n");
1894               RtsFlags.GranFlags.Debug.priSpark = rtsTrue;
1895               break;
1896
1897             case 's':       /* priSched; also -bD64 */
1898               debugBelch("DEBUG: priSched; priority scheduling.\n");
1899               RtsFlags.GranFlags.Debug.priSched = rtsTrue;
1900               break;
1901
1902             case 'F':       /* findWork; also -bD128 */
1903               debugBelch("DEBUG: findWork; searching spark-pools (local & remote), thread queues for work.\n");
1904               RtsFlags.GranFlags.Debug.findWork = rtsTrue;
1905               break;
1906               
1907             case 'g':       /* globalBlock; also -bD256 */
1908               debugBelch("DEBUG: globalBlock; blocking on remote closures (FETCHMEs etc in GUM).\n");
1909               RtsFlags.GranFlags.Debug.globalBlock = rtsTrue;
1910               break;
1911               
1912             case 'G':       /* pack; also -bD512 */
1913               debugBelch("DEBUG: pack; routines for (un-)packing graph structures.\n");
1914               RtsFlags.GranFlags.Debug.pack = rtsTrue;
1915               break;
1916               
1917             case 'P':       /* packBuffer; also -bD1024 */
1918               debugBelch("DEBUG: packBuffer; routines handling pack buffer (GranSim internal!).\n");
1919               RtsFlags.GranFlags.Debug.packBuffer = rtsTrue;
1920               break;
1921               
1922             case 'o':       /* sortedQ; also -bD2048 */
1923               debugBelch("DEBUG: sortedQ; check whether spark/thread queues are sorted.\n");
1924               RtsFlags.GranFlags.Debug.sortedQ = rtsTrue;
1925               break;
1926               
1927             case 'r':       /* randomSteal; also -bD4096 */
1928               debugBelch("DEBUG: randomSteal; stealing sparks/threads from random PEs.\n");
1929               RtsFlags.GranFlags.Debug.randomSteal = rtsTrue;
1930               break;
1931               
1932             case 'q':       /* checkSparkQ; also -bD8192 */
1933               debugBelch("DEBUG: checkSparkQ; check consistency of the spark queues.\n");
1934               RtsFlags.GranFlags.Debug.checkSparkQ = rtsTrue;
1935               break;
1936               
1937             case ':':       /* checkLight; also -bD16384 */
1938               debugBelch("DEBUG: checkLight; check GranSim-Light setup.\n");
1939               RtsFlags.GranFlags.Debug.checkLight = rtsTrue;
1940               break;
1941               
1942             case 'b':       /* bq; also -bD32768 */
1943               debugBelch("DEBUG: bq; check blocking queues\n");
1944               RtsFlags.GranFlags.Debug.bq = rtsTrue;
1945               break;
1946               
1947             case 'd':       /* all options turned on */
1948               debugBelch("DEBUG: all options turned on.\n");
1949               set_GranSim_debug_options(MAX_GRAN_DEBUG_MASK);
1950               /* RtsFlags.GranFlags.Debug |= 0x40; */
1951               break;
1952
1953 /*          case '\0': */
1954 /*            RtsFlags.GranFlags.Debug = 1; */
1955 /*            break; */
1956 #endif
1957
1958           }
1959           break;
1960 #  endif  /* GRAN_CHECK */
1961       default:
1962         bad_option( rts_argv[arg] );
1963         break;
1964       }
1965 }
1966
1967 /*
1968   Interpret n as a binary number masking GranSim debug options and set the 
1969   correxponding option. See gran_debug_opts_strs for explanations of the flags.
1970 */
1971 static void
1972 set_GranSim_debug_options(nat n) {
1973   nat i;
1974
1975   for (i=0; i<=MAX_GRAN_DEBUG_OPTION; i++) 
1976     if ((n>>i)&1) {
1977       errorBelch(gran_debug_opts_strs[i]);
1978       switch (i) {
1979         case 0: RtsFlags.GranFlags.Debug.event_trace   = rtsTrue;  break;
1980         case 1: RtsFlags.GranFlags.Debug.event_stats   = rtsTrue;  break;
1981         case 2: RtsFlags.GranFlags.Debug.bq            = rtsTrue;  break;
1982         case 3: RtsFlags.GranFlags.Debug.pack          = rtsTrue;  break;
1983         case 4: RtsFlags.GranFlags.Debug.checkSparkQ   = rtsTrue;  break;
1984         case 5: RtsFlags.GranFlags.Debug.thunkStealing = rtsTrue;  break;
1985         case 6: RtsFlags.GranFlags.Debug.randomSteal   = rtsTrue;  break;
1986         case 7: RtsFlags.GranFlags.Debug.findWork      = rtsTrue;  break;
1987         case 8: RtsFlags.GranFlags.Debug.unused        = rtsTrue;  break;
1988         case 9: RtsFlags.GranFlags.Debug.pri           = rtsTrue;  break;
1989         case 10: RtsFlags.GranFlags.Debug.checkLight   = rtsTrue;  break;
1990         case 11: RtsFlags.GranFlags.Debug.sortedQ      = rtsTrue;  break;
1991         case 12: RtsFlags.GranFlags.Debug.blockOnFetch = rtsTrue;  break;
1992         case 13: RtsFlags.GranFlags.Debug.packBuffer   = rtsTrue;  break;
1993         case 14: RtsFlags.GranFlags.Debug.blockOnFetch_sanity = rtsTrue;  break;
1994         default: barf("set_GranSim_debug_options: only %d debug options expected");
1995       } /* switch */
1996     } /* if */
1997 }
1998
1999 /*
2000   Print one line explanation for each of the GranSim debug options specified
2001   in the bitmask n.
2002 */
2003 static void
2004 help_GranSim_debug_options(nat n) {
2005   nat i;
2006
2007   for (i=0; i<=MAX_GRAN_DEBUG_OPTION; i++) 
2008     if ((n>>i)&1) 
2009       debugBelch(gran_debug_opts_strs[i]);
2010 }
2011
2012 # elif defined(PAR)
2013
2014 static void
2015 process_par_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
2016 {
2017
2018   if (rts_argv[arg][1] != 'q') { /* All GUM options start with -q */
2019     errorBelch("Warning: GUM option does not start with -q: %s", rts_argv[arg]);
2020     return;
2021   }
2022
2023   /* Communication and task creation cost parameters */
2024   switch(rts_argv[arg][2]) {
2025   case 'e':  /* -qe<n>  ... allow <n> local sparks */
2026     if (rts_argv[arg][3] != '\0') { /* otherwise, stick w/ the default */
2027       RtsFlags.ParFlags.maxLocalSparks
2028         = strtol(rts_argv[arg]+3, (char **) NULL, 10);
2029       
2030       if (RtsFlags.ParFlags.maxLocalSparks <= 0) {
2031         errorBelch("setupRtsFlags: bad value for -e\n");
2032         *error = rtsTrue;
2033       }
2034     }
2035     IF_PAR_DEBUG(verbose,
2036                  errorBelch("-qe<n>: max %d local sparks", 
2037                        RtsFlags.ParFlags.maxLocalSparks));
2038     break;
2039   
2040   case 't':
2041     if (rts_argv[arg][3] != '\0') {
2042       RtsFlags.ParFlags.maxThreads
2043         = strtol(rts_argv[arg]+3, (char **) NULL, 10);
2044     } else {
2045       errorBelch("missing size for -qt\n");
2046       *error = rtsTrue;
2047     }
2048     IF_PAR_DEBUG(verbose,
2049                  errorBelch("-qt<n>: max %d threads", 
2050                        RtsFlags.ParFlags.maxThreads));
2051     break;
2052
2053   case 'f':
2054     if (rts_argv[arg][3] != '\0')
2055       RtsFlags.ParFlags.maxFishes = decode(rts_argv[arg]+3);
2056     else
2057       RtsFlags.ParFlags.maxFishes = MAX_FISHES;
2058     break;
2059     IF_PAR_DEBUG(verbose,
2060                  errorBelch("-qf<n>: max %d fishes sent out at one time", 
2061                        RtsFlags.ParFlags.maxFishes));
2062     break;
2063   
2064   case 'F':
2065     if (rts_argv[arg][3] != '\0') {
2066       RtsFlags.ParFlags.fishDelay
2067         = strtol(rts_argv[arg]+3, (char **) NULL, 10);
2068     } else {
2069       errorBelch("missing fish delay time for -qF\n");
2070       *error = rtsTrue;
2071     }
2072     IF_PAR_DEBUG(verbose,
2073                  errorBelch("-qF<n>: fish delay time %d us", 
2074                        RtsFlags.ParFlags.fishDelay));
2075     break;
2076
2077   case 'O':
2078     RtsFlags.ParFlags.outputDisabled = rtsTrue;
2079     IF_PAR_DEBUG(verbose,
2080                  errorBelch("-qO: output disabled"));
2081     break;
2082   
2083   case 'g': /* -qg<n> ... globalisation scheme */
2084     if (rts_argv[arg][3] != '\0') {
2085       RtsFlags.ParFlags.globalising = decode(rts_argv[arg]+3);
2086     } else {
2087       errorBelch("missing identifier for globalisation scheme (for -qg)\n");
2088       *error = rtsTrue;
2089     }
2090     IF_PAR_DEBUG(verbose,
2091                  debugBelch("-qg<n>: globalisation scheme set to  %d", 
2092                        RtsFlags.ParFlags.globalising));
2093     break;
2094
2095   case 'h': /* -qh<n> ... max number of thunks (except root) in packet */
2096     if (rts_argv[arg][3] != '\0') {
2097       RtsFlags.ParFlags.thunksToPack = decode(rts_argv[arg]+3);
2098     } else {
2099       errorBelch("missing number of thunks per packet (for -qh)\n");
2100       *error = rtsTrue;
2101     }
2102     IF_PAR_DEBUG(verbose,
2103                  debugBelch("-qh<n>: thunks per packet set to %d", 
2104                        RtsFlags.ParFlags.thunksToPack));
2105     break;
2106
2107   case 'P': /* -qP for writing a log file */
2108     //RtsFlags.ParFlags.ParStats.Full = rtsFalse;
2109     /* same encoding as in GranSim after -bP */ 
2110     switch(rts_argv[arg][3]) {
2111     case '\0': RtsFlags.ParFlags.ParStats.Full = rtsTrue;
2112       break; // nothing special, just an ordinary profile
2113     case '0': RtsFlags.ParFlags.ParStats.Suppressed = rtsTrue;
2114         RtsFlags.ParFlags.ParStats.Full = rtsFalse;
2115       break;
2116     case 'b': RtsFlags.ParFlags.ParStats.Binary = rtsTrue;
2117       break;
2118     case 's': RtsFlags.ParFlags.ParStats.Sparks = rtsTrue;
2119       break;
2120       //case 'h': RtsFlags.parFlags.ParStats.Heap = rtsTrue;
2121       //  break;
2122     case 'n': RtsFlags.ParFlags.ParStats.NewLogfile = rtsTrue;
2123       break;
2124     case 'g': 
2125 # if defined(PAR_TICKY)
2126       RtsFlags.ParFlags.ParStats.Global = rtsTrue;
2127 # else 
2128       errorBelch("-qPg is only possible for a PAR_TICKY RTS, which this is not");
2129       stg_exit(EXIT_FAILURE);
2130 # endif
2131       break;
2132     default: barf("Unknown option -qP%c", rts_argv[arg][2]);
2133     }
2134     IF_PAR_DEBUG(verbose,
2135                  debugBelch("(-qP) writing to log-file (RtsFlags.ParFlags.ParStats.Full=%s)",
2136                        (RtsFlags.ParFlags.ParStats.Full ? "rtsTrue" : "rtsFalse")));
2137     break;
2138   
2139   case 'Q': /* -qQ<n> ... set pack buffer size to <n> */
2140     if (rts_argv[arg][3] != '\0') {
2141       RtsFlags.ParFlags.packBufferSize = decode(rts_argv[arg]+3);
2142     } else {
2143       errorBelch("missing size of PackBuffer (for -qQ)\n");
2144       *error = rtsTrue;
2145     }
2146     IF_PAR_DEBUG(verbose,
2147                  debugBelch("-qQ<n>: pack buffer size set to %d", 
2148                        RtsFlags.ParFlags.packBufferSize));
2149     break;
2150
2151   case 'R':
2152     RtsFlags.ParFlags.doFairScheduling = rtsTrue;
2153     IF_PAR_DEBUG(verbose,
2154                  debugBelch("-qR: fair-ish scheduling"));
2155     break;
2156   
2157 # if defined(DEBUG)  
2158   case 'w':
2159     if (rts_argv[arg][3] != '\0') {
2160       RtsFlags.ParFlags.wait
2161         = strtol(rts_argv[arg]+3, (char **) NULL, 10);
2162     } else {
2163       RtsFlags.ParFlags.wait = 1000;
2164     }
2165     IF_PAR_DEBUG(verbose,
2166                  debugBelch("-qw<n>: length of wait loop after synchr before reduction: %d", 
2167                        RtsFlags.ParFlags.wait));
2168     break;
2169
2170   case 'D':  /* -qD ... all the debugging options */
2171     if (isdigit(rts_argv[arg][3])) {/* Set all debugging options in one */
2172       /* hack warning: interpret the flags as a binary number */
2173       nat n = decode(rts_argv[arg]+3);
2174       set_par_debug_options(n);
2175     } else {
2176       nat i;
2177       for (i=0; i<=MAX_PAR_DEBUG_OPTION; i++) 
2178         if (rts_argv[arg][3] == par_debug_opts_flags[i])
2179           break;
2180         
2181       if (i==MAX_PAR_DEBUG_OPTION+1) {
2182         errorBelch("Valid GUM debug options are:\n");
2183         help_par_debug_options(MAX_PAR_DEBUG_MASK);
2184         bad_option( rts_argv[arg] );
2185       } else { // flag found; now set it
2186         set_par_debug_options(PAR_DEBUG_MASK(i));  // 2^i
2187       }
2188     }
2189     break;
2190 # endif
2191   default:
2192     errorBelch("Unknown option -q%c (%d opts in total)", 
2193           rts_argv[arg][2], *rts_argc);
2194     break;
2195   } /* switch */
2196 }
2197
2198 /*
2199   Interpret n as a binary number masking Par debug options and set the 
2200   correxponding option. See par_debug_opts_strs for explanations of the flags.
2201 */
2202 static void
2203 set_par_debug_options(nat n) {
2204   nat i;
2205
2206   for (i=0; i<=MAX_PAR_DEBUG_OPTION; i++) 
2207     if ((n>>i)&1) {
2208       debugBelch(par_debug_opts_strs[i]);
2209       switch (i) {
2210         case 0: RtsFlags.ParFlags.Debug.verbose       = rtsTrue;  break;
2211         case 1: RtsFlags.ParFlags.Debug.bq            = rtsTrue;  break;
2212         case 2: RtsFlags.ParFlags.Debug.schedule      = rtsTrue;  break;
2213         case 3: RtsFlags.ParFlags.Debug.free          = rtsTrue;  break;
2214         case 4: RtsFlags.ParFlags.Debug.resume        = rtsTrue;  break;
2215         case 5: RtsFlags.ParFlags.Debug.weight        = rtsTrue;  break;
2216         case 6: RtsFlags.ParFlags.Debug.fetch         = rtsTrue;  break;
2217           //case 7: RtsFlags.ParFlags.Debug.ack           = rtsTrue;  break;
2218         case 7: RtsFlags.ParFlags.Debug.fish          = rtsTrue;  break;
2219         case 8: RtsFlags.ParFlags.Debug.tables        = rtsTrue;  break;
2220         case 9: RtsFlags.ParFlags.Debug.packet        = rtsTrue;  break;
2221         case 10: RtsFlags.ParFlags.Debug.pack         = rtsTrue;  break;
2222         case 11: RtsFlags.ParFlags.Debug.paranoia     = rtsTrue;  break;
2223         default: barf("set_par_debug_options: only %d debug options expected",
2224                       MAX_PAR_DEBUG_OPTION);
2225       } /* switch */
2226     } /* if */
2227 }
2228
2229 /*
2230   Print one line explanation for each of the GranSim debug options specified
2231   in the bitmask n.
2232 */
2233 static void
2234 help_par_debug_options(nat n) {
2235   nat i;
2236
2237   for (i=0; i<=MAX_PAR_DEBUG_OPTION; i++) 
2238     if ((n>>i)&1) 
2239       debugBelch(par_debug_opts_strs[i]);
2240 }
2241
2242 #endif /* PAR */
2243
2244 static void
2245 stats_fprintf(FILE *f, char *s, ...)
2246 {
2247     va_list ap;
2248     va_start(ap,s);
2249     if (f == NULL) {
2250         vdebugBelch(s, ap);
2251     } else {
2252         vfprintf(f, s, ap);
2253     }
2254     va_end(ap);
2255 }
2256
2257 static int              /* return -1 on error */
2258 open_stats_file (
2259     I_ arg,
2260     int argc, char *argv[],
2261     int rts_argc, char *rts_argv[],
2262     const char *FILENAME_FMT,
2263     FILE **file_ret)
2264 {
2265     FILE *f = NULL;
2266
2267     if (strequal(rts_argv[arg]+2, "stderr")) { /* use debugBelch */
2268         f = NULL; /* NULL means use debugBelch */
2269     } else {
2270         if (rts_argv[arg][2] != '\0') {  /* stats file specified */
2271             f = fopen(rts_argv[arg]+2,"w");
2272         } else {
2273             char stats_filename[STATS_FILENAME_MAXLEN]; /* default <program>.<ext> */
2274             sprintf(stats_filename, FILENAME_FMT, argv[0]);
2275             f = fopen(stats_filename,"w");
2276         }
2277         if (f == NULL) {
2278             errorBelch("Can't open stats file %s\n", rts_argv[arg]+2);
2279             return -1;
2280         }
2281     }
2282     *file_ret = f;
2283
2284     {
2285         /* Write argv and rtsv into start of stats file */
2286         int count;
2287         for(count = 0; count < argc; count++) {
2288             stats_fprintf(f, "%s ", argv[count]);
2289         }
2290         stats_fprintf(f, "+RTS ");
2291         for(count = 0; count < rts_argc; count++)
2292             stats_fprintf(f, "%s ", rts_argv[count]);
2293         stats_fprintf(f, "\n");
2294     }
2295     return 0;
2296 }
2297
2298
2299
2300 static I_
2301 decode(const char *s)
2302 {
2303     I_ c;
2304     StgDouble m;
2305
2306     if (!*s)
2307         return 0;
2308
2309     m = atof(s);
2310     c = s[strlen(s)-1];
2311
2312     if (c == 'g' || c == 'G')
2313         m *= 1000*1000*1000;    /* UNchecked! */
2314     else if (c == 'm' || c == 'M')
2315         m *= 1000*1000;                 /* We do not use powers of 2 (1024) */
2316     else if (c == 'k' || c == 'K')      /* to avoid possible bad effects on */
2317         m *= 1000;                      /* a direct-mapped cache.           */ 
2318     else if (c == 'w' || c == 'W')
2319         m *= sizeof(W_);
2320
2321     return (I_)m;
2322 }
2323
2324 static void
2325 bad_option(const char *s)
2326 {
2327   errorBelch("bad RTS option: %s", s);
2328   stg_exit(EXIT_FAILURE);
2329 }
2330
2331 /* -----------------------------------------------------------------------------
2332    Getting/Setting the program's arguments.
2333
2334    These are used by System.Environment, and parts of the RTS.
2335    -------------------------------------------------------------------------- */
2336
2337 void
2338 setProgName(char *argv[])
2339 {
2340     /* Remove directory from argv[0] -- default files in current directory */
2341 #if !defined(mingw32_HOST_OS)
2342     char *last_slash;
2343     if ( (last_slash = (char *) strrchr(argv[0], '/')) != NULL ) {
2344         prog_name = last_slash+1;
2345    } else {
2346         prog_name = argv[0];
2347    }
2348 #else
2349     char* last_slash = argv[0] + (strlen(argv[0]) - 1);
2350     while ( last_slash > argv[0] ) {
2351         if ( *last_slash == '/' || *last_slash == '\\' ) {
2352             prog_name = last_slash+1;
2353             return;
2354         }
2355         last_slash--;
2356     }
2357     prog_name = argv[0];
2358 #endif
2359 }
2360
2361 void
2362 getProgArgv(int *argc, char **argv[])
2363 {
2364     if (argc) { *argc = prog_argc; }
2365     if (argv) { *argv = prog_argv; }
2366 }
2367
2368 void
2369 setProgArgv(int argc, char *argv[])
2370 {
2371    /* Usually this is done by startupHaskell, so we don't need to call this. 
2372       However, sometimes Hugs wants to change the arguments which Haskell
2373       getArgs >>= ... will be fed.  So you can do that by calling here
2374       _after_ calling startupHaskell.
2375    */
2376    prog_argc = argc;
2377    prog_argv = argv;
2378    setProgName(prog_argv);
2379 }