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