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