[project @ 1999-11-18 16:02:17 by sewardj]
[ghc-hetmet.git] / ghc / rts / RtsFlags.c
1 /* -----------------------------------------------------------------------------
2  * $Id: RtsFlags.c,v 1.20 1999/11/02 15:06:00 simonmar Exp $
3  *
4  * (c) The AQUA Project, Glasgow University, 1994-1997
5  * (c) The GHC Team, 1998-1999
6  *
7  * Functions for parsing the argument list.
8  *
9  * ---------------------------------------------------------------------------*/
10
11 #include "Rts.h"
12 #include "RtsFlags.h"
13 #include "RtsUtils.h"
14 #include "BlockAlloc.h"
15 #include "ProfRts.h"
16
17 #if defined(PROFILING) 
18 #include "Itimer.h"
19 #endif
20
21 #if HAVE_STDLIB_H
22 #include <stdlib.h>
23 #endif
24
25 #ifdef HAVE_STRING_H
26 #include <string.h>
27 #endif
28
29 extern struct RTS_FLAGS RtsFlags;
30
31 /*
32  * Split argument lists
33  */
34 int     prog_argc; /* an "int" so as to match normal "argc" */
35 char  **prog_argv = NULL;
36 int     rts_argc;  /* ditto */
37 char   *rts_argv[MAX_RTS_ARGS];
38
39 /*
40  * constants, used later 
41  */
42 #define RTS 1
43 #define PGM 0
44
45 /* -----------------------------------------------------------------------------
46    Static function decls
47    -------------------------------------------------------------------------- */
48
49 static FILE *           /* return NULL on error */
50 open_stats_file (
51     I_ arg,
52     int argc, char *argv[],
53     int rts_argc, char *rts_argv[],
54     const char *FILENAME_FMT);
55
56 static I_ decode(const char *s);
57 static void bad_option(const char *s);
58
59 /* -----------------------------------------------------------------------------
60  * Command-line option parsing routines.
61  * ---------------------------------------------------------------------------*/
62
63 void initRtsFlagsDefaults(void)
64 {
65     RtsFlags.GcFlags.statsFile          = NULL;
66     RtsFlags.GcFlags.giveStats          = NO_GC_STATS;
67
68     RtsFlags.GcFlags.maxStkSize         = (1024 * 1024) / sizeof(W_);
69     RtsFlags.GcFlags.initialStkSize     = 1024 / sizeof(W_);
70
71     RtsFlags.GcFlags.minAllocAreaSize   = (256 * 1024)        / BLOCK_SIZE;
72     RtsFlags.GcFlags.minOldGenSize      = (1024 * 1024)       / BLOCK_SIZE;
73     RtsFlags.GcFlags.maxHeapSize        = (64  * 1024 * 1024) / BLOCK_SIZE;
74     RtsFlags.GcFlags.heapSizeSuggestion = 0;    /* none */
75     RtsFlags.GcFlags.pcFreeHeap         = 3;    /* 3% */
76     RtsFlags.GcFlags.oldGenFactor       = 2;
77     RtsFlags.GcFlags.generations        = 2;
78     RtsFlags.GcFlags.steps              = 2;
79
80     RtsFlags.GcFlags.forceGC            = rtsFalse;
81     RtsFlags.GcFlags.forcingInterval    = 5000000; /* 5MB (or words?) */
82     RtsFlags.GcFlags.ringBell           = rtsFalse;
83
84     RtsFlags.GcFlags.squeezeUpdFrames   = rtsTrue;
85
86 #if defined(PROFILING) || defined(PAR)
87     RtsFlags.CcFlags.doCostCentres      = 0;
88     RtsFlags.CcFlags.sortBy             = SORTCC_TIME;
89 #endif /* PROFILING or PAR */
90
91 #ifdef PROFILING
92     RtsFlags.ProfFlags.doHeapProfile = rtsFalse;
93
94     RtsFlags.ProfFlags.ccSelector    = NULL;
95     RtsFlags.ProfFlags.modSelector   = NULL;
96     RtsFlags.ProfFlags.grpSelector   = NULL;
97     RtsFlags.ProfFlags.descrSelector = NULL;
98     RtsFlags.ProfFlags.typeSelector  = NULL;
99     RtsFlags.ProfFlags.kindSelector  = NULL;
100 #elif defined(DEBUG)
101     RtsFlags.ProfFlags.doHeapProfile = rtsFalse;
102 #endif
103
104     RtsFlags.ConcFlags.ctxtSwitchTime   = CS_MIN_MILLISECS;  /* In milliseconds */
105 #ifdef SMP
106     RtsFlags.ConcFlags.nNodes   = 1;
107 #endif
108 #ifdef PAR
109     RtsFlags.ParFlags.parallelStats     = rtsFalse;
110     RtsFlags.ParFlags.granSimStats      = rtsFalse;
111     RtsFlags.ParFlags.granSimStats_Binary = rtsFalse;
112
113     RtsFlags.ParFlags.outputDisabled    = rtsFalse;
114
115     RtsFlags.ParFlags.packBufferSize    = 1024;
116     RtsFlags.ParFlags.maxLocalSparks    = 4096;
117 #endif /* PAR */
118
119 #ifdef GRAN
120     RtsFlags.GranFlags.granSimStats     = rtsFalse;
121     RtsFlags.GranFlags.granSimStats_suppressed  = rtsFalse;
122     RtsFlags.GranFlags.granSimStats_Binary = rtsFalse;
123     RtsFlags.GranFlags.granSimStats_Sparks = rtsFalse;
124     RtsFlags.GranFlags.granSimStats_Heap = rtsFalse;
125     RtsFlags.GranFlags.labelling        = rtsFalse;
126     RtsFlags.GranFlags.packBufferSize   = 1024;
127     RtsFlags.GranFlags.packBufferSize_internal = GRANSIM_DEFAULT_PACK_BUFFER_SIZE;
128
129     RtsFlags.GranFlags.proc  = MAX_PROC;
130     RtsFlags.GranFlags.max_fishes = MAX_FISHES;
131     RtsFlags.GranFlags.time_slice = GRAN_TIME_SLICE;
132     RtsFlags.GranFlags.Light = rtsFalse;
133
134     RtsFlags.GranFlags.gran_latency =             LATENCY;          
135     RtsFlags.GranFlags.gran_additional_latency =  ADDITIONAL_LATENCY; 
136     RtsFlags.GranFlags.gran_fetchtime =           FETCHTIME; 
137     RtsFlags.GranFlags.gran_lunblocktime =        LOCALUNBLOCKTIME; 
138     RtsFlags.GranFlags.gran_gunblocktime =        GLOBALUNBLOCKTIME;
139     RtsFlags.GranFlags.gran_mpacktime =           MSGPACKTIME;      
140     RtsFlags.GranFlags.gran_munpacktime =         MSGUNPACKTIME;
141     RtsFlags.GranFlags.gran_mtidytime =           MSGTIDYTIME;
142
143     RtsFlags.GranFlags.gran_threadcreatetime =         THREADCREATETIME;
144     RtsFlags.GranFlags.gran_threadqueuetime =          THREADQUEUETIME;
145     RtsFlags.GranFlags.gran_threaddescheduletime =     THREADDESCHEDULETIME;
146     RtsFlags.GranFlags.gran_threadscheduletime =       THREADSCHEDULETIME;
147     RtsFlags.GranFlags.gran_threadcontextswitchtime =  THREADCONTEXTSWITCHTIME;
148
149     RtsFlags.GranFlags.gran_arith_cost =         ARITH_COST;       
150     RtsFlags.GranFlags.gran_branch_cost =        BRANCH_COST; 
151     RtsFlags.GranFlags.gran_load_cost =          LOAD_COST;        
152     RtsFlags.GranFlags.gran_store_cost =         STORE_COST; 
153     RtsFlags.GranFlags.gran_float_cost =         FLOAT_COST;       
154
155     RtsFlags.GranFlags.gran_heapalloc_cost =     HEAPALLOC_COST;
156
157     RtsFlags.GranFlags.gran_pri_spark_overhead = PRI_SPARK_OVERHEAD;        
158     RtsFlags.GranFlags.gran_pri_sched_overhead = PRI_SCHED_OVERHEAD;        
159
160     RtsFlags.GranFlags.DoFairSchedule = rtsFalse;             
161     RtsFlags.GranFlags.DoReScheduleOnFetch = rtsFalse;        
162     RtsFlags.GranFlags.DoStealThreadsFirst = rtsFalse;        
163     RtsFlags.GranFlags.SimplifiedFetch = rtsFalse;            
164     RtsFlags.GranFlags.DoAlwaysCreateThreads = rtsFalse;      
165     RtsFlags.GranFlags.DoGUMMFetching = rtsFalse;             
166     RtsFlags.GranFlags.DoThreadMigration = rtsFalse;          
167     RtsFlags.GranFlags.FetchStrategy = 2;                     
168     RtsFlags.GranFlags.PreferSparksOfLocalNodes = rtsFalse;   
169     RtsFlags.GranFlags.DoPrioritySparking = rtsFalse;         
170     RtsFlags.GranFlags.DoPriorityScheduling = rtsFalse;       
171     RtsFlags.GranFlags.SparkPriority = 0;
172     RtsFlags.GranFlags.SparkPriority2 = 0; 
173     RtsFlags.GranFlags.RandomPriorities = rtsFalse;           
174     RtsFlags.GranFlags.InversePriorities = rtsFalse;          
175     RtsFlags.GranFlags.IgnorePriorities = rtsFalse;           
176     RtsFlags.GranFlags.ThunksToPack = 0;                      
177     RtsFlags.GranFlags.RandomSteal = rtsTrue;
178     RtsFlags.GranFlags.NoForward = rtsFalse;
179     RtsFlags.GranFlags.PrintFetchMisses = rtsFalse;
180
181     RtsFlags.GranFlags.debug = 0x0;
182     RtsFlags.GranFlags.event_trace = rtsFalse;
183     RtsFlags.GranFlags.event_trace_all = rtsFalse;
184 #endif
185
186 #ifdef TICKY_TICKY
187     RtsFlags.TickyFlags.showTickyStats   = rtsFalse;
188     RtsFlags.TickyFlags.tickyFile        = NULL;
189 #endif
190 }
191
192 static const char *
193 usage_text[] = {
194 "",
195 "Usage: <prog> <args> [+RTS <rtsopts> | -RTS <args>] ... --RTS <args>",
196 "",
197 "   +RTS    Indicates run time system options follow",
198 "   -RTS    Indicates program arguments follow",
199 "  --RTS    Indicates that ALL subsequent arguments will be given to the",
200 "           program (including any of these RTS flags)",
201 "",
202 "The following run time system options are available:",
203 "",
204 "  -? -f    Prints this message and exits; the program is not executed",
205 "",
206 "  -K<size> Sets the maximum stack size (default 1M)  Egs: -K32k   -K512k",
207 "  -k<size> Sets the initial thread stack size (default 1k)  Egs: -K4k   -K2m",
208 "",
209 "  -A<size> Sets the minimum allocation area size (default 256k) Egs: -A1m -A10k",
210 "  -M<size> Sets the maximum heap size (default 64M)  Egs: -M256k -M1G",
211 "  -H<size> Sets the minimum heap size (default 0M)   Egs: -H24m  -H1G",
212 "  -m<n>%   Minimum % of heap which must be available (default 3%)",
213 "  -G<n>    Number of generations (default: 2)",
214 "  -T<n>    Number of steps in younger generations (default: 2)",
215 "  -s<file> Summary GC statistics   (default file: <program>.stat)",
216 "  -S<file> Detailed GC statistics  (with -Sstderr going to stderr)",
217 "",
218 "",
219 "  -Z       Don't squeeze out update frames on stack overflow",
220 "  -B       Sound the bell at the start of each garbage collection",
221 #if defined(PROFILING) || defined(PAR)
222 "",
223 "  -p<sort> Produce cost centre time profile  (output file <program>.prof)",
224 "             sort: T = time (default), A = alloc, C = cost centre label",
225 "  -P<sort> Produce serial time profile (output file <program>.time)",
226 "             and a -p profile with detailed tick/alloc info",
227 # if defined(PROFILING)
228 "",
229 "  -h<break-down> Heap residency profile      (output file <program>.hp)",
230 "     break-down: C = cost centre stack (default), M = module, G = group",
231 "                 D = closure description, Y = type description",
232 "                 T<ints>,<start> = time closure created",
233 "                    ints:  no. of interval bands plotted (default 18)",
234 "                    start: seconds after which intervals start (default 0.0)",
235 "  A subset of closures may be selected by the attached cost centre using:",
236 "    -c{mod:lab,mod:lab...}, specific module:label cost centre(s)",
237 "    -m{mod,mod...} all cost centres from the specified modules(s)",
238 "    -g{grp,grp...} all cost centres from the specified group(s)",
239 "  Selections can also be made by description, type, kind and age:",
240 "    -d{des,des...} closures with specified closure descriptions",
241 "    -y{typ,typ...} closures with specified type descriptions",
242 "    -k{knd,knd...} closures of the specified kinds",
243 "    -a<age>        closures which survived <age> complete intervals",
244 "  The selection logic used is summarised as follows:",
245 "    ([-c] or [-m] or [-g]) and ([-d] or [-y] or [-k]) and [-a]",
246 "    where an option is true if not specified",
247 # endif
248 "",
249 "  -z<tbl><size>  set hash table <size> for <tbl> (C, M, G, D or Y)",
250 "",
251 "  -i<secs> Number of seconds in a profiling interval (default 1.0):",
252 "           heap profile (-h) and/or serial time profile (-P) frequency",
253 #endif /* PROFILING or PAR */
254 #if !defined(PROFILING) && defined(DEBUG)
255 "",
256 "  -h<break-down> Debugging Heap residency profile",
257 "                 (output file <program>.hp)",
258 "     break-down: L = closure label (default)",
259 "                 T = closure type (constructor, thunk etc.)",
260 #endif
261 "",
262 #if defined(TICKY_TICKY)
263 "  -r<file>  Produce reduction profiling statistics (with -rstderr for stderr)",
264 "",
265 #endif
266 # ifdef PAR
267 "  -N<n>     Use <n> PVMish processors in parallel (default: 2)",
268 /* NB: the -N<n> is implemented by the driver!! */
269 # endif
270 "  -C<secs>  Context-switch interval in seconds",
271 "                (0 or no argument means switch as often as possible)",
272 "                the default is .01 sec; resolution is .01 sec",
273 # ifdef SMP
274 "  -N<n>     Use <n> OS threads (default: 1)",
275 # endif
276 # ifdef PAR
277 "  -q        Enable activity profile (output files in ~/<program>*.gr)",
278 "  -qb       Enable binary activity profile (output file /tmp/<program>.gb)",
279 "  -Q<size>  Set pack-buffer size (default: 1024)",
280 # endif
281 # ifdef PAR
282 "  -d        Turn on PVM-ish debugging",
283 "  -O        Disable output for performance measurement",
284 # endif /* PAR */
285 # ifdef GRAN  /* ToDo: fill in decent Docu here */
286 "  -b...     All GranSim options start with -b; see GranSim User's Guide for details",
287 # endif
288 "",
289 "Other RTS options may be available for programs compiled a different way.",
290 "The GHC User's Guide has full details.",
291 "",
292 0
293 };
294
295 static __inline__ rtsBool
296 strequal(const char *a, const char * b)
297 {
298     return(strcmp(a, b) == 0);
299 }
300
301 void
302 setupRtsFlags(int *argc, char *argv[], int *rts_argc, char *rts_argv[])
303 {
304     rtsBool error = rtsFalse;
305     I_ mode;
306     I_ arg, total_arg;
307     char *last_slash;
308
309     /* Remove directory from argv[0] -- default files in current directory */
310
311     if ((last_slash = (char *) strrchr(argv[0], '/')) != NULL)
312         strcpy(argv[0], last_slash+1);
313
314     /* Split arguments (argv) into PGM (argv) and RTS (rts_argv) parts */
315     /*   argv[0] must be PGM argument -- leave in argv                 */
316
317     total_arg = *argc;
318     arg = 1;
319
320     *argc = 1;
321     *rts_argc = 0;
322
323     for (mode = PGM; arg < total_arg && ! strequal("--RTS", argv[arg]); arg++) {
324         if (strequal("+RTS", argv[arg])) {
325             mode = RTS;
326         }
327         else if (strequal("-RTS", argv[arg])) {
328             mode = PGM;
329         }
330         else if (mode == RTS && *rts_argc < MAX_RTS_ARGS-1) {
331             rts_argv[(*rts_argc)++] = argv[arg];
332         }
333         else if (mode == PGM) {
334             argv[(*argc)++] = argv[arg];
335         }
336         else {
337           barf("too many RTS arguments (max %d)", MAX_RTS_ARGS-1);
338         }
339     }
340     if (arg < total_arg) {
341         /* arg must be --RTS; process remaining program arguments */
342         while (++arg < total_arg) {
343             argv[(*argc)++] = argv[arg];
344         }
345     }
346     argv[*argc] = (char *) 0;
347     rts_argv[*rts_argc] = (char *) 0;
348
349     /* Process RTS (rts_argv) part: mainly to determine statsfile */
350
351     for (arg = 0; arg < *rts_argc; arg++) {
352         if (rts_argv[arg][0] != '-') {
353             fflush(stdout);
354             fprintf(stderr, "setupRtsFlags: Unexpected RTS argument: %s\n",
355                     rts_argv[arg]);
356             error = rtsTrue;
357
358         } else {
359             switch(rts_argv[arg][1]) {
360
361               /* process: general args, then PROFILING-only ones,
362                  then CONCURRENT-only, PARallel-only, GRAN-only,
363                  TICKY-only (same order as defined in RtsFlags.lh);
364                  within those groups, mostly in case-insensitive
365                  alphabetical order.
366               */
367
368 #ifdef TICKY_TICKY
369 # define TICKY_BUILD_ONLY(x) x
370 #else
371 # define TICKY_BUILD_ONLY(x) \
372 fprintf(stderr, "setupRtsFlags: GHC not built for: ticky-ticky stats\n"); \
373 error = rtsTrue;
374 #endif
375
376 #if defined(PROFILING) 
377 # define COST_CENTRE_USING_BUILD_ONLY(x) x
378 #else
379 # define COST_CENTRE_USING_BUILD_ONLY(x) \
380 fprintf(stderr, "setupRtsFlags: GHC not built for: -prof or -parallel\n"); \
381 error = rtsTrue;
382 #endif
383
384 #ifdef PROFILING
385 # define PROFILING_BUILD_ONLY(x)   x
386 #else
387 # define PROFILING_BUILD_ONLY(x) \
388 fprintf(stderr, "setupRtsFlags: GHC not built for: -prof\n"); \
389 error = rtsTrue;
390 #endif
391
392 #ifdef PAR
393 # define PAR_BUILD_ONLY(x)      x
394 #else
395 # define PAR_BUILD_ONLY(x) \
396 fprintf(stderr, "setupRtsFlags: GHC not built for: -parallel\n"); \
397 error = rtsTrue;
398 #endif
399
400 #ifdef GRAN
401 # define GRAN_BUILD_ONLY(x)     x
402 #else
403 # define GRAN_BUILD_ONLY(x) \
404 fprintf(stderr, "setupRtsFlags: GHC not built for: -gransim\n"); \
405 error = rtsTrue;
406 #endif
407
408               /* =========== GENERAL ========================== */
409               case '?':
410               case 'f':
411                 error = rtsTrue;
412                 break;
413
414               case 'A':
415                 RtsFlags.GcFlags.minAllocAreaSize
416                   = decode(rts_argv[arg]+2) / BLOCK_SIZE;
417                 if (RtsFlags.GcFlags.minAllocAreaSize <= 0) {
418                   bad_option(rts_argv[arg]);
419                 }
420                 break;
421
422               case 'B':
423                 RtsFlags.GcFlags.ringBell = rtsTrue;
424                 break;
425
426               case 'F':
427                 RtsFlags.GcFlags.oldGenFactor = atof(rts_argv[arg]+2);
428               
429                 if (RtsFlags.GcFlags.oldGenFactor < 0)
430                   bad_option( rts_argv[arg] );
431                 break;
432               
433 #ifdef DEBUG
434               case 'D':
435                 /* hack warning: interpret the flags as a binary number */
436                 { 
437                    I_ n = decode(rts_argv[arg]+2);
438                    if (n     &1) RtsFlags.DebugFlags.scheduler   = rtsTrue;
439                    if ((n>>1)&1) RtsFlags.DebugFlags.evaluator   = rtsTrue;
440                    if ((n>>2)&1) RtsFlags.DebugFlags.codegen     = rtsTrue;
441                    if ((n>>3)&1) RtsFlags.DebugFlags.weak        = rtsTrue;
442                    if ((n>>4)&1) RtsFlags.DebugFlags.gccafs      = rtsTrue;
443                    if ((n>>5)&1) RtsFlags.DebugFlags.gc          = rtsTrue;
444                    if ((n>>6)&1) RtsFlags.DebugFlags.block_alloc = rtsTrue;
445                    if ((n>>7)&1) RtsFlags.DebugFlags.sanity      = rtsTrue;
446                    if ((n>>8)&1) RtsFlags.DebugFlags.stable      = rtsTrue;
447                    if ((n>>9)&1) RtsFlags.DebugFlags.prof        = rtsTrue;
448                 }
449                 break;
450 #endif
451
452               case 'K':
453                 RtsFlags.GcFlags.maxStkSize = 
454                   decode(rts_argv[arg]+2) / sizeof(W_);
455
456                 if (RtsFlags.GcFlags.maxStkSize == 0) 
457                   bad_option( rts_argv[arg] );
458                 break;
459
460               case 'k':
461                 RtsFlags.GcFlags.initialStkSize = 
462                   decode(rts_argv[arg]+2) / sizeof(W_);
463
464                 if (RtsFlags.GcFlags.initialStkSize == 0) 
465                   bad_option( rts_argv[arg] );
466                 break;
467
468               case 'M':
469                 RtsFlags.GcFlags.maxHeapSize = 
470                   decode(rts_argv[arg]+2) / BLOCK_SIZE;
471                 /* user give size in *bytes* but "maxHeapSize" is in *blocks* */
472
473                 if (RtsFlags.GcFlags.maxHeapSize <= 0) {
474                   bad_option(rts_argv[arg]);
475                 }
476                 break;
477
478               case 'm':
479                 RtsFlags.GcFlags.pcFreeHeap = atof(rts_argv[arg]+2);
480
481                 if (RtsFlags.GcFlags.pcFreeHeap < 0 || 
482                     RtsFlags.GcFlags.pcFreeHeap > 100)
483                   bad_option( rts_argv[arg] );
484                 break;
485
486               case 'G':
487                 RtsFlags.GcFlags.generations = decode(rts_argv[arg]+2);
488                 if (RtsFlags.GcFlags.generations < 1) {
489                   bad_option(rts_argv[arg]);
490                 }
491                 break;
492
493               case 'T':
494                 RtsFlags.GcFlags.steps = decode(rts_argv[arg]+2);
495                 if (RtsFlags.GcFlags.steps < 1) {
496                   bad_option(rts_argv[arg]);
497                 }
498                 break;
499
500               case 'H':
501                 RtsFlags.GcFlags.heapSizeSuggestion = 
502                   decode(rts_argv[arg]+2) / BLOCK_SIZE;
503
504                 if (RtsFlags.GcFlags.heapSizeSuggestion <= 0) {
505                   bad_option(rts_argv[arg]);
506                 }
507                 break;
508
509               case 'j': /* force GC option */
510                 RtsFlags.GcFlags.forceGC = rtsTrue;
511                 if (rts_argv[arg][2]) {
512                     RtsFlags.GcFlags.forcingInterval
513                         = decode(rts_argv[arg]+2) / sizeof(W_);
514                 }
515                 break;
516
517               case 'S':
518                 RtsFlags.GcFlags.giveStats ++;
519
520               case 's':
521                 RtsFlags.GcFlags.giveStats ++;
522 #ifdef PAR
523                 /* Opening all those files would almost certainly fail... */
524                 RtsFlags.ParFlags.parallelStats = rtsTrue;
525                 RtsFlags.GcFlags.statsFile = stderr; /* temporary; ToDo: rm */
526 #else
527                 RtsFlags.GcFlags.statsFile
528                   = open_stats_file(arg, *argc, argv,
529                         *rts_argc, rts_argv, STAT_FILENAME_FMT);
530
531                 if (RtsFlags.GcFlags.statsFile == NULL) error = rtsTrue;
532 #endif
533                 break;
534
535               case 'Z':
536                 RtsFlags.GcFlags.squeezeUpdFrames = rtsFalse;
537                 break;
538
539               /* =========== PROFILING ========================== */
540
541               case 'P': /* detailed cost centre profiling (time/alloc) */
542                 COST_CENTRE_USING_BUILD_ONLY(
543                 RtsFlags.CcFlags.doCostCentres++;
544                 )
545               case 'p': /* cost centre profiling (time/alloc) */
546                 COST_CENTRE_USING_BUILD_ONLY(
547                 RtsFlags.CcFlags.doCostCentres++;
548
549                 switch (rts_argv[arg][2]) {
550                   case SORTCC_LABEL:
551                   case SORTCC_TIME:
552                   case SORTCC_ALLOC:
553                         RtsFlags.CcFlags.sortBy = rts_argv[arg][2];
554                     break;
555                   default:
556                         RtsFlags.CcFlags.sortBy = SORTCC_TIME;
557                     break;
558                 }
559                 ) break;
560
561               case 'i': /* serial profiling -- initial timer interval */
562                 COST_CENTRE_USING_BUILD_ONLY(
563                 interval_ticks = (I_) ((atof(rts_argv[arg]+2) * TICK_FREQUENCY));
564                 if (interval_ticks <= 0)
565                     interval_ticks = 1;
566                 ) break;
567
568               case 'h': /* serial heap profile */
569 #if !defined(PROFILING) && defined(DEBUG)
570                 switch (rts_argv[arg][2]) {
571                   case '\0':
572                   case 'L':
573                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_INFOPTR;
574                     break;
575                   case 'T':
576                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CLOSURE_TYPE;
577                     break;
578                   default:
579                     fprintf(stderr, "Invalid heap profile option: %s\n",
580                             rts_argv[arg]);
581                     error = rtsTrue;
582                 }
583 #else
584                 PROFILING_BUILD_ONLY(
585                 switch (rts_argv[arg][2]) {
586                   case '\0':
587                   case CCchar:
588                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CCS;
589                     break;
590                   case MODchar:
591                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_MOD;
592                     break;
593                   case GRPchar:
594                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_GRP;
595                     break;
596                   case DESCRchar:
597                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_DESCR;
598                     break;
599                   case TYPEchar:
600                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_TYPE;
601                     break;
602                   case TIMEchar:
603                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_TIME;
604                     if (rts_argv[arg][3]) {
605                         char *start_str = strchr(rts_argv[arg]+3, ',');
606                         I_ intervals;
607                         if (start_str) *start_str = '\0';
608
609                         if ((intervals = decode(rts_argv[arg]+3)) != 0) {
610                             time_intervals = (hash_t) intervals;
611                             /* ToDo: and what if it *is* zero intervals??? */
612                         }
613                         if (start_str) {
614                             earlier_ticks = (I_)((atof(start_str + 1) * TICK_FREQUENCY));
615                         }
616                     }
617                     break;
618                   default:
619                     fprintf(stderr, "Invalid heap profile option: %s\n",
620                             rts_argv[arg]);
621                     error = rtsTrue;
622                 }
623                 ) 
624 #endif
625                 break;
626
627               case 'z': /* size of index tables */
628                 PROFILING_BUILD_ONLY(
629                 switch (rts_argv[arg][2]) {
630                   case CCchar:
631                     max_cc_no = (hash_t) decode(rts_argv[arg]+3);
632                     if (max_cc_no == 0) {
633                         fprintf(stderr, "Bad number of cost centres %s\n", rts_argv[arg]);
634                         error = rtsTrue;
635                     }
636                     break;
637                   case MODchar:
638                     max_mod_no = (hash_t) decode(rts_argv[arg]+3);
639                     if (max_mod_no == 0) {
640                         fprintf(stderr, "Bad number of modules %s\n", rts_argv[arg]);
641                         error = rtsTrue;
642                     }
643                     break;
644                   case GRPchar:
645                     max_grp_no = (hash_t) decode(rts_argv[arg]+3);
646                     if (max_grp_no == 0) {
647                         fprintf(stderr, "Bad number of groups %s\n", rts_argv[arg]);
648                         error = rtsTrue;
649                     }
650                     break;
651                   case DESCRchar:
652                     max_descr_no = (hash_t) decode(rts_argv[arg]+3);
653                     if (max_descr_no == 0) {
654                         fprintf(stderr, "Bad number of closure descriptions %s\n", rts_argv[arg]);
655                         error = rtsTrue;
656                     }
657                     break;
658                   case TYPEchar:
659                     max_type_no = (hash_t) decode(rts_argv[arg]+3);
660                     if (max_type_no == 0) {
661                         fprintf(stderr, "Bad number of type descriptions %s\n", rts_argv[arg]);
662                         error = rtsTrue;
663                     }
664                     break;
665                   default:
666                     fprintf(stderr, "Invalid index table size option: %s\n",
667                             rts_argv[arg]);
668                     error = rtsTrue;
669                 }
670                 ) break;
671
672               case 'c': /* cost centre label select */
673               case 'g': /* cost centre group select */
674               case 'd': /* closure descr select */
675               case 'y': /* closure type select */
676                 PROFILING_BUILD_ONLY(
677                 {char *left  = strchr(rts_argv[arg], '{');
678                  char *right = strrchr(rts_argv[arg], '}');
679
680                 if (! left || ! right ||
681                         strrchr(rts_argv[arg], '{') != left ||
682                          strchr(rts_argv[arg], '}') != right) {
683                     fprintf(stderr, "Invalid heap profiling selection bracketing\n   %s\n", rts_argv[arg]);
684                     error = rtsTrue;
685                 } else {
686                     *right = '\0';
687                     switch (rts_argv[arg][1]) {
688                       case 'c': /* cost centre label select */
689                         RtsFlags.ProfFlags.ccSelector = left + 1;
690                         break;
691                       case 'm': /* cost centre module select */
692                         RtsFlags.ProfFlags.modSelector = left + 1;
693                         break;
694                       case 'g': /* cost centre group select */
695                         RtsFlags.ProfFlags.grpSelector = left + 1;
696                         break;
697                       case 'd': /* closure descr select */
698                         RtsFlags.ProfFlags.descrSelector = left + 1;
699                         break;
700                       case 'y': /* closure type select */
701                         RtsFlags.ProfFlags.typeSelector = left + 1;
702                         break;
703                       case 'k': /* closure kind select */
704                         RtsFlags.ProfFlags.kindSelector = left + 1;
705                         break;
706                     }
707                 }}
708                 ) break;
709
710               /* =========== CONCURRENT ========================= */
711               case 'C': /* context switch interval */
712                 if (rts_argv[arg][2] == '\0')
713                     RtsFlags.ConcFlags.ctxtSwitchTime = 0;
714                 else {
715                     I_ cst; /* tmp */
716
717                     /* Convert to milliseconds */
718                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
719                     cst = (cst / CS_MIN_MILLISECS) * CS_MIN_MILLISECS;
720                     if (cst < CS_MIN_MILLISECS)
721                         cst = CS_MIN_MILLISECS;
722
723                     RtsFlags.ConcFlags.ctxtSwitchTime = cst;
724                 }
725                 break;
726
727 #ifdef SMP
728               case 'N':
729                 if (rts_argv[arg][2] != '\0') {
730                     RtsFlags.ConcFlags.nNodes
731                       = strtol(rts_argv[arg]+2, (char **) NULL, 10);
732                     if (RtsFlags.ConcFlags.nNodes <= 0) {
733                         fprintf(stderr, "setupRtsFlags: bad value for -N\n");
734                         error = rtsTrue;
735                     }
736                 }
737                 break;
738 #endif
739               /* =========== PARALLEL =========================== */
740               case 'e':
741                 PAR_BUILD_ONLY(
742                 if (rts_argv[arg][2] != '\0') { /* otherwise, stick w/ the default */
743
744                     RtsFlags.ParFlags.maxLocalSparks
745                       = strtol(rts_argv[arg]+2, (char **) NULL, 10);
746
747                     if (RtsFlags.ParFlags.maxLocalSparks <= 0) {
748                         fprintf(stderr, "setupRtsFlags: bad value for -e\n");
749                         error = rtsTrue;
750                     }
751                 }
752                 ) break;
753
754               case 'O':
755                 PAR_BUILD_ONLY(
756                 RtsFlags.ParFlags.outputDisabled = rtsTrue;
757                 ) break;
758
759               case 'q': /* activity profile option */
760                 PAR_BUILD_ONLY(
761                 if (rts_argv[arg][2] == 'b')
762                     RtsFlags.ParFlags.granSimStats_Binary = rtsTrue;
763                 else
764                     RtsFlags.ParFlags.granSimStats = rtsTrue;
765                 ) break;
766
767 #if 0 /* or??? */
768               case 'q': /* quasi-parallel profile option */
769                 GRAN_BUILD_ONLY (
770                 if (rts_argv[arg][2] == 'v')
771                     do_qp_prof = 2;
772                 else
773                     do_qp_prof++;
774                 ) break;
775 #endif /* 0??? */
776
777               case 'Q': /* Set pack buffer size */
778                 PAR_BUILD_ONLY(
779                 if (rts_argv[arg][2] != '\0') {
780                     RtsFlags.ParFlags.packBufferSize = decode(rts_argv[arg]+2);
781                 } else {
782                     fprintf(stderr, "setupRtsFlags: missing size of PackBuffer (for -Q)\n");
783                     error = rtsTrue;
784                 }
785                 ) break;
786
787               /* =========== GRAN =============================== */
788
789               case 'b':
790                 GRAN_BUILD_ONLY(
791                 process_gran_option(arg, rts_argc, rts_argv, &error);
792                 ) break;
793
794               /* =========== TICKY ============================== */
795
796               case 'r': /* Basic profiling stats */
797                 TICKY_BUILD_ONLY(
798
799                 RtsFlags.TickyFlags.showTickyStats = rtsTrue;
800                 RtsFlags.TickyFlags.tickyFile
801                   = open_stats_file(arg, *argc, argv,
802                         *rts_argc, rts_argv, TICKY_FILENAME_FMT);
803
804                 if (RtsFlags.TickyFlags.tickyFile == NULL) error = rtsTrue;
805                 ) break;
806
807               /* =========== OH DEAR ============================ */
808               default:
809                 fprintf(stderr, "setupRtsFlags: Unknown RTS option: %s\n",rts_argv[arg]);
810                 error = rtsTrue;
811                 break;
812             }
813         }
814     }
815     if (error) {
816         const char **p;
817
818         fflush(stdout);
819         for (p = usage_text; *p; p++)
820             fprintf(stderr, "%s\n", *p);
821         stg_exit(EXIT_FAILURE);
822     }
823
824 }
825
826 static FILE *           /* return NULL on error */
827 open_stats_file (
828     I_ arg,
829     int argc, char *argv[],
830     int rts_argc, char *rts_argv[],
831     const char *FILENAME_FMT)
832 {
833     FILE *f = NULL;
834
835     if (strequal(rts_argv[arg]+2, "stderr")) /* use real stderr */
836         f = stderr;
837     else if (rts_argv[arg][2] != '\0')      /* stats file specified */
838         f = fopen(rts_argv[arg]+2,"w");
839     else {
840         char stats_filename[STATS_FILENAME_MAXLEN]; /* default <program>.<ext> */
841         sprintf(stats_filename, FILENAME_FMT, argv[0]);
842         f = fopen(stats_filename,"w");
843     }
844     if (f == NULL) {
845         fprintf(stderr, "Can't open stats file %s\n", rts_argv[arg]+2);
846     } else {
847         /* Write argv and rtsv into start of stats file */
848         I_ count;
849         for(count = 0; count < argc; count++)
850             fprintf(f, "%s ", argv[count]);
851         fprintf(f, "+RTS ");
852         for(count = 0; count < rts_argc; count++)
853             fprintf(f, "%s ", rts_argv[count]);
854         fprintf(f, "\n");
855     }
856
857     return(f);
858 }
859
860 static I_
861 decode(const char *s)
862 {
863     I_ c;
864     StgDouble m;
865
866     if (!*s)
867         return 0;
868
869     m = atof(s);
870     c = s[strlen(s)-1];
871
872     if (c == 'g' || c == 'G')
873         m *= 1000*1000*1000;    /* UNchecked! */
874     else if (c == 'm' || c == 'M')
875         m *= 1000*1000;                 /* We do not use powers of 2 (1024) */
876     else if (c == 'k' || c == 'K')      /* to avoid possible bad effects on */
877         m *= 1000;                      /* a direct-mapped cache.           */ 
878     else if (c == 'w' || c == 'W')
879         m *= sizeof(W_);
880
881     return (I_)m;
882 }
883
884 static void
885 bad_option(const char *s)
886 {
887   fflush(stdout);
888   fprintf(stderr, "initSM: Bad RTS option: %s\n", s);
889   stg_exit(EXIT_FAILURE);
890 }