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