[project @ 1999-01-21 10:31:41 by simonm]
[ghc-hetmet.git] / ghc / rts / RtsFlags.c
1 /* -----------------------------------------------------------------------------
2  * $Id: RtsFlags.c,v 1.6 1999/01/21 10:31:48 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.minOldGenSize      = (1024 * 1024)       / BLOCK_SIZE;
66     RtsFlags.GcFlags.maxHeapSize        = (64  * 1024 * 1024) / BLOCK_SIZE;
67     RtsFlags.GcFlags.pcFreeHeap         = 3;    /* 3% */
68     RtsFlags.GcFlags.oldGenFactor       = 2;
69     RtsFlags.GcFlags.generations        = 2;
70
71     RtsFlags.GcFlags.forceGC            = rtsFalse;
72     RtsFlags.GcFlags.forcingInterval    = 5000000; /* 5MB (or words?) */
73     RtsFlags.GcFlags.ringBell           = rtsFalse;
74
75     RtsFlags.GcFlags.squeezeUpdFrames   = rtsTrue;
76
77 #if defined(PROFILING) || defined(PAR)
78     RtsFlags.CcFlags.doCostCentres      = 0;
79     RtsFlags.CcFlags.sortBy             = SORTCC_TIME;
80 #endif /* PROFILING or PAR */
81
82 #ifdef PROFILING
83     RtsFlags.ProfFlags.doHeapProfile = rtsFalse;
84
85     RtsFlags.ProfFlags.ccSelector    = NULL;
86     RtsFlags.ProfFlags.modSelector   = NULL;
87     RtsFlags.ProfFlags.grpSelector   = NULL;
88     RtsFlags.ProfFlags.descrSelector = NULL;
89     RtsFlags.ProfFlags.typeSelector  = NULL;
90     RtsFlags.ProfFlags.kindSelector  = NULL;
91 #elif defined(DEBUG)
92     RtsFlags.ProfFlags.doHeapProfile = rtsFalse;
93 #endif
94
95 /* there really shouldn't be a threads limit for concurrent mandatory threads.
96    For now, unlimitied means less than 64k (there's a storage overhead) -- SOF
97 */
98 #if defined(CONCURRENT) && !defined(GRAN)
99     RtsFlags.ConcFlags.ctxtSwitchTime   = CS_MIN_MILLISECS;  /* In milliseconds */
100     RtsFlags.ConcFlags.maxThreads       = 65536;
101     RtsFlags.ConcFlags.stkChunkSize     = 1024;
102     RtsFlags.ConcFlags.maxLocalSparks   = 65536;
103 #endif /* CONCURRENT only */
104
105 #if GRAN
106     RtsFlags.ConcFlags.ctxtSwitchTime   = CS_MIN_MILLISECS;  /* In milliseconds */
107     RtsFlags.ConcFlags.maxThreads       = 32;
108     RtsFlags.ConcFlags.stkChunkSize     = 1024;
109     RtsFlags.ConcFlags.maxLocalSparks   = 500;
110 #endif /* GRAN */
111
112 #ifdef PAR
113     RtsFlags.ParFlags.parallelStats     = rtsFalse;
114     RtsFlags.ParFlags.granSimStats      = rtsFalse;
115     RtsFlags.ParFlags.granSimStats_Binary = rtsFalse;
116
117     RtsFlags.ParFlags.outputDisabled    = rtsFalse;
118
119     RtsFlags.ParFlags.packBufferSize    = 1024;
120     RtsFlags.ParFlags.maxLocalSparks    = 4096;
121 #endif /* PAR */
122
123 #ifdef GRAN
124     RtsFlags.GranFlags.granSimStats     = rtsFalse;
125     RtsFlags.GranFlags.granSimStats_suppressed  = rtsFalse;
126     RtsFlags.GranFlags.granSimStats_Binary = rtsFalse;
127     RtsFlags.GranFlags.granSimStats_Sparks = rtsFalse;
128     RtsFlags.GranFlags.granSimStats_Heap = rtsFalse;
129     RtsFlags.GranFlags.labelling        = rtsFalse;
130     RtsFlags.GranFlags.packBufferSize   = 1024;
131     RtsFlags.GranFlags.packBufferSize_internal = GRANSIM_DEFAULT_PACK_BUFFER_SIZE;
132
133     RtsFlags.GranFlags.proc  = MAX_PROC;
134     RtsFlags.GranFlags.max_fishes = MAX_FISHES;
135     RtsFlags.GranFlags.time_slice = GRAN_TIME_SLICE;
136     RtsFlags.GranFlags.Light = rtsFalse;
137
138     RtsFlags.GranFlags.gran_latency =             LATENCY;          
139     RtsFlags.GranFlags.gran_additional_latency =  ADDITIONAL_LATENCY; 
140     RtsFlags.GranFlags.gran_fetchtime =           FETCHTIME; 
141     RtsFlags.GranFlags.gran_lunblocktime =        LOCALUNBLOCKTIME; 
142     RtsFlags.GranFlags.gran_gunblocktime =        GLOBALUNBLOCKTIME;
143     RtsFlags.GranFlags.gran_mpacktime =           MSGPACKTIME;      
144     RtsFlags.GranFlags.gran_munpacktime =         MSGUNPACKTIME;
145     RtsFlags.GranFlags.gran_mtidytime =           MSGTIDYTIME;
146
147     RtsFlags.GranFlags.gran_threadcreatetime =         THREADCREATETIME;
148     RtsFlags.GranFlags.gran_threadqueuetime =          THREADQUEUETIME;
149     RtsFlags.GranFlags.gran_threaddescheduletime =     THREADDESCHEDULETIME;
150     RtsFlags.GranFlags.gran_threadscheduletime =       THREADSCHEDULETIME;
151     RtsFlags.GranFlags.gran_threadcontextswitchtime =  THREADCONTEXTSWITCHTIME;
152
153     RtsFlags.GranFlags.gran_arith_cost =         ARITH_COST;       
154     RtsFlags.GranFlags.gran_branch_cost =        BRANCH_COST; 
155     RtsFlags.GranFlags.gran_load_cost =          LOAD_COST;        
156     RtsFlags.GranFlags.gran_store_cost =         STORE_COST; 
157     RtsFlags.GranFlags.gran_float_cost =         FLOAT_COST;       
158
159     RtsFlags.GranFlags.gran_heapalloc_cost =     HEAPALLOC_COST;
160
161     RtsFlags.GranFlags.gran_pri_spark_overhead = PRI_SPARK_OVERHEAD;        
162     RtsFlags.GranFlags.gran_pri_sched_overhead = PRI_SCHED_OVERHEAD;        
163
164     RtsFlags.GranFlags.DoFairSchedule = rtsFalse;             
165     RtsFlags.GranFlags.DoReScheduleOnFetch = rtsFalse;        
166     RtsFlags.GranFlags.DoStealThreadsFirst = rtsFalse;        
167     RtsFlags.GranFlags.SimplifiedFetch = rtsFalse;            
168     RtsFlags.GranFlags.DoAlwaysCreateThreads = rtsFalse;      
169     RtsFlags.GranFlags.DoGUMMFetching = rtsFalse;             
170     RtsFlags.GranFlags.DoThreadMigration = rtsFalse;          
171     RtsFlags.GranFlags.FetchStrategy = 2;                     
172     RtsFlags.GranFlags.PreferSparksOfLocalNodes = rtsFalse;   
173     RtsFlags.GranFlags.DoPrioritySparking = rtsFalse;         
174     RtsFlags.GranFlags.DoPriorityScheduling = rtsFalse;       
175     RtsFlags.GranFlags.SparkPriority = 0;
176     RtsFlags.GranFlags.SparkPriority2 = 0; 
177     RtsFlags.GranFlags.RandomPriorities = rtsFalse;           
178     RtsFlags.GranFlags.InversePriorities = rtsFalse;          
179     RtsFlags.GranFlags.IgnorePriorities = rtsFalse;           
180     RtsFlags.GranFlags.ThunksToPack = 0;                      
181     RtsFlags.GranFlags.RandomSteal = rtsTrue;
182     RtsFlags.GranFlags.NoForward = rtsFalse;
183     RtsFlags.GranFlags.PrintFetchMisses = rtsFalse;
184
185     RtsFlags.GranFlags.debug = 0x0;
186     RtsFlags.GranFlags.event_trace = rtsFalse;
187     RtsFlags.GranFlags.event_trace_all = rtsFalse;
188 #endif
189
190 #ifdef TICKY_TICKY
191     RtsFlags.TickyFlags.showTickyStats  = rtsFalse;
192     RtsFlags.TickyFlags.tickyFile       = NULL;
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               case 'F':
433                 RtsFlags.GcFlags.oldGenFactor = atof(rts_argv[arg]+2);
434               
435                 if (RtsFlags.GcFlags.oldGenFactor < 0)
436                   bad_option( rts_argv[arg] );
437                 break;
438               
439 #ifdef DEBUG
440               case 'D':
441                 /* hack warning: interpret the flags as a binary number */
442                 *(int*)(&RtsFlags.DebugFlags) = decode(rts_argv[arg]+2);
443                 break;
444 #endif
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 'G':
481                 RtsFlags.GcFlags.generations = decode(rts_argv[arg]+2);
482                 if (RtsFlags.GcFlags.generations < 1) {
483                   bad_option(rts_argv[arg]);
484                 }
485                 break;
486
487               case 'H':
488                 /* ignore for compatibility with older versions */
489                 break;
490
491               case 'j': /* force GC option */
492                 RtsFlags.GcFlags.forceGC = rtsTrue;
493                 if (rts_argv[arg][2]) {
494                     RtsFlags.GcFlags.forcingInterval
495                         = decode(rts_argv[arg]+2) / sizeof(W_);
496                 }
497                 break;
498
499               case 'S': /* NB: no difference at present ! */
500               case 's':
501                 RtsFlags.GcFlags.giveStats ++; /* will be VERBOSE_GC_STATS */
502 #ifdef PAR
503                 /* Opening all those files would almost certainly fail... */
504                 RtsFlags.ParFlags.parallelStats = rtsTrue;
505                 RtsFlags.GcFlags.statsFile = stderr; /* temporary; ToDo: rm */
506 #else
507                 RtsFlags.GcFlags.statsFile
508                   = open_stats_file(arg, *argc, argv,
509                         *rts_argc, rts_argv, STAT_FILENAME_FMT);
510
511                 if (RtsFlags.GcFlags.statsFile == NULL) error = rtsTrue;
512 #endif
513                 break;
514
515               case 'Z':
516                 RtsFlags.GcFlags.squeezeUpdFrames = rtsFalse;
517                 break;
518
519               /* =========== PROFILING ========================== */
520
521               case 'P': /* detailed cost centre profiling (time/alloc) */
522                 COST_CENTRE_USING_BUILD_ONLY(
523                 RtsFlags.CcFlags.doCostCentres++;
524                 )
525               case 'p': /* cost centre profiling (time/alloc) */
526                 COST_CENTRE_USING_BUILD_ONLY(
527                 RtsFlags.CcFlags.doCostCentres++;
528
529                 switch (rts_argv[arg][2]) {
530                   case SORTCC_LABEL:
531                   case SORTCC_TIME:
532                   case SORTCC_ALLOC:
533                         RtsFlags.CcFlags.sortBy = rts_argv[arg][2];
534                     break;
535                   default:
536                         RtsFlags.CcFlags.sortBy = SORTCC_TIME;
537                     break;
538                 }
539                 ) break;
540
541               case 'i': /* serial profiling -- initial timer interval */
542                 COST_CENTRE_USING_BUILD_ONLY(
543                 interval_ticks = (I_) ((atof(rts_argv[arg]+2) * TICK_FREQUENCY));
544                 if (interval_ticks <= 0)
545                     interval_ticks = 1;
546                 ) break;
547
548               case 'h': /* serial heap profile */
549 #if !defined(PROFILING) && defined(DEBUG)
550                 switch (rts_argv[arg][2]) {
551                   case '\0':
552                   case 'L':
553                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_INFOPTR;
554                     break;
555                   case 'T':
556                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CLOSURE_TYPE;
557                     break;
558                   default:
559                     fprintf(stderr, "Invalid heap profile option: %s\n",
560                             rts_argv[arg]);
561                     error = rtsTrue;
562                 }
563 #else
564                 PROFILING_BUILD_ONLY(
565                 switch (rts_argv[arg][2]) {
566                   case '\0':
567                   case CCchar:
568                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CC;
569                     break;
570                   case MODchar:
571                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_MOD;
572                     break;
573                   case GRPchar:
574                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_GRP;
575                     break;
576                   case DESCRchar:
577                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_DESCR;
578                     break;
579                   case TYPEchar:
580                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_TYPE;
581                     break;
582                   case TIMEchar:
583                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_TIME;
584                     if (rts_argv[arg][3]) {
585                         char *start_str = strchr(rts_argv[arg]+3, ',');
586                         I_ intervals;
587                         if (start_str) *start_str = '\0';
588
589                         if ((intervals = decode(rts_argv[arg]+3)) != 0) {
590                             time_intervals = (hash_t) intervals;
591                             /* ToDo: and what if it *is* zero intervals??? */
592                         }
593                         if (start_str) {
594                             earlier_ticks = (I_)((atof(start_str + 1) * TICK_FREQUENCY));
595                         }
596                     }
597                     break;
598                   default:
599                     fprintf(stderr, "Invalid heap profile option: %s\n",
600                             rts_argv[arg]);
601                     error = rtsTrue;
602                 }
603                 ) 
604 #endif
605                 break;
606
607               case 'z': /* size of index tables */
608                 PROFILING_BUILD_ONLY(
609                 switch (rts_argv[arg][2]) {
610                   case CCchar:
611                     max_cc_no = (hash_t) decode(rts_argv[arg]+3);
612                     if (max_cc_no == 0) {
613                         fprintf(stderr, "Bad number of cost centres %s\n", rts_argv[arg]);
614                         error = rtsTrue;
615                     }
616                     break;
617                   case MODchar:
618                     max_mod_no = (hash_t) decode(rts_argv[arg]+3);
619                     if (max_mod_no == 0) {
620                         fprintf(stderr, "Bad number of modules %s\n", rts_argv[arg]);
621                         error = rtsTrue;
622                     }
623                     break;
624                   case GRPchar:
625                     max_grp_no = (hash_t) decode(rts_argv[arg]+3);
626                     if (max_grp_no == 0) {
627                         fprintf(stderr, "Bad number of groups %s\n", rts_argv[arg]);
628                         error = rtsTrue;
629                     }
630                     break;
631                   case DESCRchar:
632                     max_descr_no = (hash_t) decode(rts_argv[arg]+3);
633                     if (max_descr_no == 0) {
634                         fprintf(stderr, "Bad number of closure descriptions %s\n", rts_argv[arg]);
635                         error = rtsTrue;
636                     }
637                     break;
638                   case TYPEchar:
639                     max_type_no = (hash_t) decode(rts_argv[arg]+3);
640                     if (max_type_no == 0) {
641                         fprintf(stderr, "Bad number of type descriptions %s\n", rts_argv[arg]);
642                         error = rtsTrue;
643                     }
644                     break;
645                   default:
646                     fprintf(stderr, "Invalid index table size option: %s\n",
647                             rts_argv[arg]);
648                     error = rtsTrue;
649                 }
650                 ) break;
651
652               case 'c': /* cost centre label select */
653               case 'g': /* cost centre group select */
654               case 'd': /* closure descr select */
655               case 'y': /* closure type select */
656                 PROFILING_BUILD_ONLY(
657                 {char *left  = strchr(rts_argv[arg], '{');
658                  char *right = strrchr(rts_argv[arg], '}');
659
660                 if (! left || ! right ||
661                         strrchr(rts_argv[arg], '{') != left ||
662                          strchr(rts_argv[arg], '}') != right) {
663                     fprintf(stderr, "Invalid heap profiling selection bracketing\n   %s\n", rts_argv[arg]);
664                     error = rtsTrue;
665                 } else {
666                     *right = '\0';
667                     switch (rts_argv[arg][1]) {
668                       case 'c': /* cost centre label select */
669                         RtsFlags.ProfFlags.ccSelector = left + 1;
670                         break;
671                       case 'm': /* cost centre module select */
672                         RtsFlags.ProfFlags.modSelector = left + 1;
673                         break;
674                       case 'g': /* cost centre group select */
675                         RtsFlags.ProfFlags.grpSelector = left + 1;
676                         break;
677                       case 'd': /* closure descr select */
678                         RtsFlags.ProfFlags.descrSelector = left + 1;
679                         break;
680                       case 'y': /* closure type select */
681                         RtsFlags.ProfFlags.typeSelector = left + 1;
682                         break;
683                       case 'k': /* closure kind select */
684                         RtsFlags.ProfFlags.kindSelector = left + 1;
685                         break;
686                     }
687                 }}
688                 ) break;
689
690               /* =========== CONCURRENT ========================= */
691               case 'C': /* context switch interval */
692                 if (rts_argv[arg][2] == '\0')
693                     RtsFlags.ConcFlags.ctxtSwitchTime = 0;
694                 else {
695                     I_ cst; /* tmp */
696
697                     /* Convert to milliseconds */
698                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
699                     cst = (cst / CS_MIN_MILLISECS) * CS_MIN_MILLISECS;
700                     if (cst < CS_MIN_MILLISECS)
701                         cst = CS_MIN_MILLISECS;
702
703                     RtsFlags.ConcFlags.ctxtSwitchTime = cst;
704                 }
705                 break;
706
707               case 't':
708                 if (rts_argv[arg][2] != '\0') {
709                     RtsFlags.ConcFlags.maxThreads
710                       = strtol(rts_argv[arg]+2, (char **) NULL, 10);
711                 } else {
712                     fprintf(stderr, "setupRtsFlags: missing size for -t\n");
713                     error = rtsTrue;
714                 }
715                 break;
716
717               /* =========== PARALLEL =========================== */
718               case 'e':
719                 PAR_BUILD_ONLY(
720                 if (rts_argv[arg][2] != '\0') { /* otherwise, stick w/ the default */
721
722                     RtsFlags.ParFlags.maxLocalSparks
723                       = strtol(rts_argv[arg]+2, (char **) NULL, 10);
724
725                     if (RtsFlags.ParFlags.maxLocalSparks <= 0) {
726                         fprintf(stderr, "setupRtsFlags: bad value for -e\n");
727                         error = rtsTrue;
728                     }
729                 }
730                 ) break;
731
732               case 'O':
733                 PAR_BUILD_ONLY(
734                 RtsFlags.ParFlags.outputDisabled = rtsTrue;
735                 ) break;
736
737               case 'q': /* activity profile option */
738                 PAR_BUILD_ONLY(
739                 if (rts_argv[arg][2] == 'b')
740                     RtsFlags.ParFlags.granSimStats_Binary = rtsTrue;
741                 else
742                     RtsFlags.ParFlags.granSimStats = rtsTrue;
743                 ) break;
744
745 #if 0 /* or??? */
746               case 'q': /* quasi-parallel profile option */
747                 GRAN_BUILD_ONLY (
748                 if (rts_argv[arg][2] == 'v')
749                     do_qp_prof = 2;
750                 else
751                     do_qp_prof++;
752                 ) break;
753 #endif /* 0??? */
754
755               case 'Q': /* Set pack buffer size */
756                 PAR_BUILD_ONLY(
757                 if (rts_argv[arg][2] != '\0') {
758                     RtsFlags.ParFlags.packBufferSize = decode(rts_argv[arg]+2);
759                 } else {
760                     fprintf(stderr, "setupRtsFlags: missing size of PackBuffer (for -Q)\n");
761                     error = rtsTrue;
762                 }
763                 ) break;
764
765               /* =========== GRAN =============================== */
766
767               case 'b':
768                 GRAN_BUILD_ONLY(
769                 process_gran_option(arg, rts_argc, rts_argv, &error);
770                 ) break;
771
772               /* =========== TICKY ============================== */
773
774               case 'r': /* Basic profiling stats */
775                 TICKY_BUILD_ONLY(
776
777                 RtsFlags.TickyFlags.showTickyStats = rtsTrue;
778                 RtsFlags.TickyFlags.tickyFile
779                   = open_stats_file(arg, *argc, argv,
780                         *rts_argc, rts_argv, TICKY_FILENAME_FMT);
781
782                 if (RtsFlags.TickyFlags.tickyFile == NULL) error = rtsTrue;
783                 ) break;
784
785               /* =========== OH DEAR ============================ */
786               default:
787                 fprintf(stderr, "setupRtsFlags: Unknown RTS option: %s\n",rts_argv[arg]);
788                 error = rtsTrue;
789                 break;
790             }
791         }
792     }
793     if (error) {
794         const char **p;
795
796         fflush(stdout);
797         for (p = usage_text; *p; p++)
798             fprintf(stderr, "%s\n", *p);
799         stg_exit(EXIT_FAILURE);
800     }
801
802 }
803
804 static FILE *           /* return NULL on error */
805 open_stats_file (
806     I_ arg,
807     int argc, char *argv[],
808     int rts_argc, char *rts_argv[],
809     const char *FILENAME_FMT)
810 {
811     FILE *f = NULL;
812
813     if (strequal(rts_argv[arg]+2, "stderr")) /* use real stderr */
814         f = stderr;
815     else if (rts_argv[arg][2] != '\0')      /* stats file specified */
816         f = fopen(rts_argv[arg]+2,"w");
817     else {
818         char stats_filename[STATS_FILENAME_MAXLEN]; /* default <program>.<ext> */
819         sprintf(stats_filename, FILENAME_FMT, argv[0]);
820         f = fopen(stats_filename,"w");
821     }
822     if (f == NULL) {
823         fprintf(stderr, "Can't open stats file %s\n", rts_argv[arg]+2);
824     } else {
825         /* Write argv and rtsv into start of stats file */
826         I_ count;
827         for(count = 0; count < argc; count++)
828             fprintf(f, "%s ", argv[count]);
829         fprintf(f, "+RTS ");
830         for(count = 0; count < rts_argc; count++)
831             fprintf(f, "%s ", rts_argv[count]);
832         fprintf(f, "\n");
833     }
834
835     return(f);
836 }
837
838 static I_
839 decode(const char *s)
840 {
841     I_ c;
842     StgDouble m;
843
844     if (!*s)
845         return 0;
846
847     m = atof(s);
848     c = s[strlen(s)-1];
849
850     if (c == 'g' || c == 'G')
851         m *= 1000*1000*1000;    /* UNchecked! */
852     else if (c == 'm' || c == 'M')
853         m *= 1000*1000;                 /* We do not use powers of 2 (1024) */
854     else if (c == 'k' || c == 'K')      /* to avoid possible bad effects on */
855         m *= 1000;                      /* a direct-mapped cache.           */ 
856     else if (c == 'w' || c == 'W')
857         m *= sizeof(W_);
858
859     return (I_)m;
860 }
861
862 static void
863 bad_option(const char *s)
864 {
865   fflush(stdout);
866   fprintf(stderr, "initSM: Bad RTS option: %s\n", s);
867   stg_exit(EXIT_FAILURE);
868 }