[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / rts / RtsFlags.c
1 /* -----------------------------------------------------------------------------
2  * $Id: RtsFlags.c,v 1.2 1998/12/02 13:28:39 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
68     RtsFlags.GcFlags.force2s            = rtsFalse;
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 "  -s<file> Summary GC statistics   (default file: <program>.stat)",
217 "  -S<file> Detailed GC statistics  (with -Sstderr going to stderr)",
218 "",
219 "",
220 "  -Z       Don't squeeze out update frames on stack overflow",
221 "  -B       Sound the bell at the start of each garbage collection",
222 #if defined(PROFILING) || defined(PAR)
223 "",
224 "  -p<sort> Produce cost centre time profile  (output file <program>.prof)",
225 "             sort: T = time (default), A = alloc, C = cost centre label",
226 "  -P<sort> Produce serial time profile (output file <program>.time)",
227 "             and a -p profile with detailed tick/alloc info",
228 # if defined(PROFILING)
229 "",
230 "  -h<break-down> Heap residency profile      (output file <program>.hp)",
231 "     break-down: C = cost centre (default), M = module, G = group",
232 "                 D = closure description, Y = type description",
233 "                 T<ints>,<start> = time closure created",
234 "                    ints:  no. of interval bands plotted (default 18)",
235 "                    start: seconds after which intervals start (default 0.0)",
236 "  A subset of closures may be selected by the attached cost centre using:",
237 "    -c{mod:lab,mod:lab...}, specific module:label cost centre(s)",
238 "    -m{mod,mod...} all cost centres from the specified modules(s)",
239 "    -g{grp,grp...} all cost centres from the specified group(s)",
240 "  Selections can also be made by description, type, kind and age:",
241 "    -d{des,des...} closures with specified closure descriptions",
242 "    -y{typ,typ...} closures with specified type descriptions",
243 "    -k{knd,knd...} closures of the specified kinds",
244 "    -a<age>        closures which survived <age> complete intervals",
245 "  The selection logic used is summarised as follows:",
246 "    ([-c] or [-m] or [-g]) and ([-d] or [-y] or [-k]) and [-a]",
247 "    where an option is true if not specified",
248 # endif
249 "",
250 "  -z<tbl><size>  set hash table <size> for <tbl> (C, M, G, D or Y)",
251 "",
252 "  -i<secs> Number of seconds in a profiling interval (default 1.0):",
253 "           heap profile (-h) and/or serial time profile (-P) frequency",
254 #endif /* PROFILING or PAR */
255 #if !defined(PROFILING) && defined(DEBUG)
256 "",
257 "  -h<break-down> Debugging Heap residency profile",
258 "                 (output file <program>.hp)",
259 "     break-down: L = closure label (default)",
260 "                 T = closure type (constructor, thunk etc.)",
261 #endif
262 "",
263 #if defined(TICKY_TICKY)
264 "  -r<file>  Produce reduction profiling statistics (with -rstderr for stderr)",
265 "",
266 #endif
267 "  -T<level> Trace garbage collection execution (debugging)",
268 "",
269 # ifdef PAR
270 "  -N<n>     Use <n> PVMish processors in parallel (default: 2)",
271 /* NB: the -N<n> is implemented by the driver!! */
272 # endif
273 "  -C<secs>  Context-switch interval in seconds",
274 "                (0 or no argument means switch as often as possible)",
275 "                the default is .01 sec; resolution is .01 sec",
276 "  -e<size>        Size of spark pools (default 100)",
277 # ifdef PAR
278 "  -q        Enable activity profile (output files in ~/<program>*.gr)",
279 "  -qb       Enable binary activity profile (output file /tmp/<program>.gb)",
280 "  -Q<size>  Set pack-buffer size (default: 1024)",
281 # else
282 "  -q[v]     Enable quasi-parallel profile (output file <program>.qp)",
283 # endif
284 "  -t<num>   Set maximum number of advisory threads per PE (default 32)",
285 "  -o<num>   Set stack chunk size (default 1024)",
286 # ifdef PAR
287 "  -d        Turn on PVM-ish debugging",
288 "  -O        Disable output for performance measurement",
289 # endif /* PAR */
290 # ifdef GRAN  /* ToDo: fill in decent Docu here */
291 "  -b...     All GranSim options start with -b; see GranSim User's Guide for details",
292 # endif
293 "",
294 "Other RTS options may be available for programs compiled a different way.",
295 "The GHC User's Guide has full details.",
296 "",
297 0
298 };
299
300 static __inline__ rtsBool
301 strequal(const char *a, const char * b)
302 {
303     return(strcmp(a, b) == 0);
304 }
305
306 void
307 setupRtsFlags(int *argc, char *argv[], int *rts_argc, char *rts_argv[])
308 {
309     rtsBool error = rtsFalse;
310     I_ mode;
311     I_ arg, total_arg;
312     char *last_slash;
313
314     /* Remove directory from argv[0] -- default files in current directory */
315
316     if ((last_slash = (char *) strrchr(argv[0], '/')) != NULL)
317         strcpy(argv[0], last_slash+1);
318
319     /* Split arguments (argv) into PGM (argv) and RTS (rts_argv) parts */
320     /*   argv[0] must be PGM argument -- leave in argv                 */
321
322     total_arg = *argc;
323     arg = 1;
324
325     *argc = 1;
326     *rts_argc = 0;
327
328     for (mode = PGM; arg < total_arg && ! strequal("--RTS", argv[arg]); arg++) {
329         if (strequal("+RTS", argv[arg])) {
330             mode = RTS;
331         }
332         else if (strequal("-RTS", argv[arg])) {
333             mode = PGM;
334         }
335         else if (mode == RTS && *rts_argc < MAX_RTS_ARGS-1) {
336             rts_argv[(*rts_argc)++] = argv[arg];
337         }
338         else if (mode == PGM) {
339             argv[(*argc)++] = argv[arg];
340         }
341         else {
342           barf("too many RTS arguments (max %d)", MAX_RTS_ARGS-1);
343         }
344     }
345     if (arg < total_arg) {
346         /* arg must be --RTS; process remaining program arguments */
347         while (++arg < total_arg) {
348             argv[(*argc)++] = argv[arg];
349         }
350     }
351     argv[*argc] = (char *) 0;
352     rts_argv[*rts_argc] = (char *) 0;
353
354     /* Process RTS (rts_argv) part: mainly to determine statsfile */
355
356     for (arg = 0; arg < *rts_argc; arg++) {
357         if (rts_argv[arg][0] != '-') {
358             fflush(stdout);
359             fprintf(stderr, "setupRtsFlags: Unexpected RTS argument: %s\n",
360                     rts_argv[arg]);
361             error = rtsTrue;
362
363         } else {
364             switch(rts_argv[arg][1]) {
365
366               /* process: general args, then PROFILING-only ones,
367                  then CONCURRENT-only, PARallel-only, GRAN-only,
368                  TICKY-only (same order as defined in RtsFlags.lh);
369                  within those groups, mostly in case-insensitive
370                  alphabetical order.
371               */
372
373 #ifdef TICKY_TICKY
374 # define TICKY_BUILD_ONLY(x) x
375 #else
376 # define TICKY_BUILD_ONLY(x) \
377 fprintf(stderr, "setupRtsFlags: GHC not built for: ticky-ticky stats\n"); \
378 error = rtsTrue;
379 #endif
380
381 #if defined(PROFILING) 
382 # define COST_CENTRE_USING_BUILD_ONLY(x) x
383 #else
384 # define COST_CENTRE_USING_BUILD_ONLY(x) \
385 fprintf(stderr, "setupRtsFlags: GHC not built for: -prof or -parallel\n"); \
386 error = rtsTrue;
387 #endif
388
389 #ifdef PROFILING
390 # define PROFILING_BUILD_ONLY(x)   x
391 #else
392 # define PROFILING_BUILD_ONLY(x) \
393 fprintf(stderr, "setupRtsFlags: GHC not built for: -prof\n"); \
394 error = rtsTrue;
395 #endif
396
397 #ifdef PAR
398 # define PAR_BUILD_ONLY(x)      x
399 #else
400 # define PAR_BUILD_ONLY(x) \
401 fprintf(stderr, "setupRtsFlags: GHC not built for: -parallel\n"); \
402 error = rtsTrue;
403 #endif
404
405 #ifdef GRAN
406 # define GRAN_BUILD_ONLY(x)     x
407 #else
408 # define GRAN_BUILD_ONLY(x) \
409 fprintf(stderr, "setupRtsFlags: GHC not built for: -gransim\n"); \
410 error = rtsTrue;
411 #endif
412
413               /* =========== GENERAL ========================== */
414               case '?':
415               case 'f':
416                 error = rtsTrue;
417                 break;
418
419               case 'A':
420                 RtsFlags.GcFlags.minAllocAreaSize
421                   = decode(rts_argv[arg]+2) / BLOCK_SIZE;
422                 if (RtsFlags.GcFlags.minAllocAreaSize <= 0) {
423                   bad_option(rts_argv[arg]);
424                 }
425                 break;
426
427               case 'B':
428                 RtsFlags.GcFlags.ringBell = rtsTrue;
429                 break;
430
431 #ifdef DEBUG
432               case 'D':
433                 /* hack warning: interpret the flags as a binary number */
434                 *(int*)(&RtsFlags.DebugFlags) = decode(rts_argv[arg]+2);
435                 break;
436 #endif
437
438               case 'F':
439                 if (strequal(rts_argv[arg]+2, "2s")) {
440                     RtsFlags.GcFlags.force2s = rtsTrue;
441                 } else {
442                     bad_option( rts_argv[arg] );
443                 }
444                 break;
445
446               case 'K':
447                 RtsFlags.GcFlags.maxStkSize = 
448                   decode(rts_argv[arg]+2) / sizeof(W_);
449
450                 if (RtsFlags.GcFlags.maxStkSize == 0) 
451                   bad_option( rts_argv[arg] );
452                 break;
453
454               case 'k':
455                 RtsFlags.GcFlags.initialStkSize = 
456                   decode(rts_argv[arg]+2) / sizeof(W_);
457
458                 if (RtsFlags.GcFlags.initialStkSize == 0) 
459                   bad_option( rts_argv[arg] );
460                 break;
461
462               case 'M':
463                 RtsFlags.GcFlags.maxHeapSize = 
464                   decode(rts_argv[arg]+2) / BLOCK_SIZE;
465                 /* user give size in *bytes* but "maxHeapSize" is in *blocks* */
466
467                 if (RtsFlags.GcFlags.maxHeapSize <= 0) {
468                   bad_option(rts_argv[arg]);
469                 }
470                 break;
471
472               case 'm':
473                 RtsFlags.GcFlags.pcFreeHeap = atof(rts_argv[arg]+2);
474
475                 if (RtsFlags.GcFlags.pcFreeHeap < 0 || 
476                     RtsFlags.GcFlags.pcFreeHeap > 100)
477                   bad_option( rts_argv[arg] );
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 }