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