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