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