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