Unify event logging and debug tracing.
[ghc-hetmet.git] / rts / RtsFlags.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The AQUA Project, Glasgow University, 1994-1997
4  * (c) The GHC Team, 1998-2006
5  *
6  * Functions for parsing the argument list.
7  *
8  * ---------------------------------------------------------------------------*/
9
10 #include "PosixSource.h"
11 #include "Rts.h"
12
13 #include "RtsUtils.h"
14 #include "Profiling.h"
15
16 #ifdef HAVE_CTYPE_H
17 #include <ctype.h>
18 #endif
19
20 #include <string.h>
21
22 // Flag Structure
23 RTS_FLAGS RtsFlags;
24
25 /*
26  * Split argument lists
27  */
28 int     prog_argc = 0;    /* an "int" so as to match normal "argc" */
29 char  **prog_argv = NULL;
30 int     full_prog_argc = 0;    /* an "int" so as to match normal "argc" */
31 char  **full_prog_argv = NULL;
32 char   *prog_name = NULL; /* 'basename' of prog_argv[0] */
33 int     rts_argc = 0;  /* ditto */
34 char   *rts_argv[MAX_RTS_ARGS];
35
36 /*
37  * constants, used later 
38  */
39 #define RTS 1
40 #define PGM 0
41
42 /* -----------------------------------------------------------------------------
43    Static function decls
44    -------------------------------------------------------------------------- */
45
46 static int              /* return NULL on error */
47 open_stats_file (
48     I_ arg,
49     int argc, char *argv[],
50     int rts_argc, char *rts_argv[],
51     const char *FILENAME_FMT,
52     FILE **file_ret);
53
54 static I_ decode(const char *s);
55 static void bad_option(const char *s);
56
57 /* -----------------------------------------------------------------------------
58  * Command-line option parsing routines.
59  * ---------------------------------------------------------------------------*/
60
61 void initRtsFlagsDefaults(void)
62 {
63     RtsFlags.GcFlags.statsFile          = NULL;
64     RtsFlags.GcFlags.giveStats          = NO_GC_STATS;
65
66     RtsFlags.GcFlags.maxStkSize         = (8 * 1024 * 1024) / sizeof(W_);
67     RtsFlags.GcFlags.initialStkSize     = 1024 / sizeof(W_);
68
69     RtsFlags.GcFlags.minAllocAreaSize   = (512 * 1024)        / BLOCK_SIZE;
70     RtsFlags.GcFlags.minOldGenSize      = (1024 * 1024)       / BLOCK_SIZE;
71     RtsFlags.GcFlags.maxHeapSize        = 0;    /* off by default */
72     RtsFlags.GcFlags.heapSizeSuggestion = 0;    /* none */
73     RtsFlags.GcFlags.pcFreeHeap         = 3;    /* 3% */
74     RtsFlags.GcFlags.oldGenFactor       = 2;
75     RtsFlags.GcFlags.generations        = 2;
76     RtsFlags.GcFlags.steps              = 2;
77     RtsFlags.GcFlags.squeezeUpdFrames   = rtsTrue;
78     RtsFlags.GcFlags.compact            = rtsFalse;
79     RtsFlags.GcFlags.compactThreshold   = 30.0;
80     RtsFlags.GcFlags.sweep              = rtsFalse;
81 #ifdef RTS_GTK_FRONTPANEL
82     RtsFlags.GcFlags.frontpanel         = rtsFalse;
83 #endif
84     RtsFlags.GcFlags.idleGCDelayTime    = 300; /* millisecs */
85
86 #if osf3_HOST_OS
87 /* ToDo: Perhaps by adjusting this value we can make linking without
88  * -static work (i.e., not generate a core-dumping executable)? */
89 # if SIZEOF_VOID_P == 8
90     RtsFlags.GcFlags.heapBase           = 0x180000000L;
91 # else
92 #  error I have no idea where to begin the heap on a non-64-bit osf3 machine.
93 # endif
94 #else
95     RtsFlags.GcFlags.heapBase           = 0;   /* means don't care */
96 #endif
97
98 #ifdef DEBUG
99     RtsFlags.DebugFlags.scheduler       = rtsFalse;
100     RtsFlags.DebugFlags.interpreter     = rtsFalse;
101     RtsFlags.DebugFlags.weak            = rtsFalse;
102     RtsFlags.DebugFlags.gccafs          = rtsFalse;
103     RtsFlags.DebugFlags.gc              = rtsFalse;
104     RtsFlags.DebugFlags.block_alloc     = rtsFalse;
105     RtsFlags.DebugFlags.sanity          = rtsFalse;
106     RtsFlags.DebugFlags.stable          = rtsFalse;
107     RtsFlags.DebugFlags.stm             = rtsFalse;
108     RtsFlags.DebugFlags.prof            = rtsFalse;
109     RtsFlags.DebugFlags.apply           = rtsFalse;
110     RtsFlags.DebugFlags.linker          = rtsFalse;
111     RtsFlags.DebugFlags.squeeze         = rtsFalse;
112     RtsFlags.DebugFlags.hpc             = rtsFalse;
113     RtsFlags.DebugFlags.sparks          = rtsFalse;
114 #endif
115
116 #if defined(PROFILING)
117     RtsFlags.CcFlags.doCostCentres      = 0;
118 #endif /* PROFILING */
119
120     RtsFlags.ProfFlags.doHeapProfile      = rtsFalse;
121     RtsFlags.ProfFlags.profileInterval    = 100;
122
123 #ifdef PROFILING
124     RtsFlags.ProfFlags.includeTSOs        = rtsFalse;
125     RtsFlags.ProfFlags.showCCSOnException = rtsFalse;
126     RtsFlags.ProfFlags.maxRetainerSetSize = 8;
127     RtsFlags.ProfFlags.ccsLength          = 25;
128     RtsFlags.ProfFlags.modSelector        = NULL;
129     RtsFlags.ProfFlags.descrSelector      = NULL;
130     RtsFlags.ProfFlags.typeSelector       = NULL;
131     RtsFlags.ProfFlags.ccSelector         = NULL;
132     RtsFlags.ProfFlags.ccsSelector        = NULL;
133     RtsFlags.ProfFlags.retainerSelector   = NULL;
134     RtsFlags.ProfFlags.bioSelector        = NULL;
135 #endif
136
137 #ifdef TRACING
138     RtsFlags.TraceFlags.trace_stderr  = rtsFalse;
139     RtsFlags.TraceFlags.timestamp     = rtsFalse;
140     RtsFlags.TraceFlags.scheduler     = rtsFalse;
141 #endif
142
143     RtsFlags.MiscFlags.tickInterval     = 20;  /* In milliseconds */
144     RtsFlags.ConcFlags.ctxtSwitchTime   = 20;  /* In milliseconds */
145
146     RtsFlags.MiscFlags.install_signal_handlers = rtsTrue;
147     RtsFlags.MiscFlags.machineReadable = rtsFalse;
148     RtsFlags.MiscFlags.linkerMemBase    = 0;
149
150 #ifdef THREADED_RTS
151     RtsFlags.ParFlags.nNodes            = 1;
152     RtsFlags.ParFlags.migrate           = rtsTrue;
153     RtsFlags.ParFlags.wakeupMigrate     = rtsFalse;
154     RtsFlags.ParFlags.parGcEnabled      = 1;
155     RtsFlags.ParFlags.parGcGen          = 1;
156     RtsFlags.ParFlags.parGcLoadBalancing = 1;
157     RtsFlags.ParFlags.setAffinity       = 0;
158 #endif
159
160 #if defined(THREADED_RTS)
161     RtsFlags.ParFlags.maxLocalSparks    = 4096;
162 #endif /* THREADED_RTS */
163
164 #ifdef TICKY_TICKY
165     RtsFlags.TickyFlags.showTickyStats   = rtsFalse;
166     RtsFlags.TickyFlags.tickyFile        = NULL;
167 #endif
168
169 #ifdef USE_PAPI
170     /* By default no special measurements taken */
171     RtsFlags.PapiFlags.eventType        = 0;
172     RtsFlags.PapiFlags.numUserEvents    = 0;
173 #endif
174 }
175
176 static const char *
177 usage_text[] = {
178 "",
179 "Usage: <prog> <args> [+RTS <rtsopts> | -RTS <args>] ... --RTS <args>",
180 "",
181 "   +RTS    Indicates run time system options follow",
182 "   -RTS    Indicates program arguments follow",
183 "  --RTS    Indicates that ALL subsequent arguments will be given to the",
184 "           program (including any of these RTS flags)",
185 "",
186 "The following run time system options are available:",
187 "",
188 "  -?       Prints this message and exits; the program is not executed",
189 "  --info   Print information about the RTS used by this program",
190 "",
191 "  -K<size> Sets the maximum stack size (default 8M)  Egs: -K32k   -K512k",
192 "  -k<size> Sets the initial thread stack size (default 1k)  Egs: -k4k   -k2m",
193 "",
194 "  -A<size> Sets the minimum allocation area size (default 512k) Egs: -A1m -A10k",
195 "  -M<size> Sets the maximum heap size (default unlimited)  Egs: -M256k -M1G",
196 "  -H<size> Sets the minimum heap size (default 0M)   Egs: -H24m  -H1G",
197 "  -m<n>    Minimum % of heap which must be available (default 3%)",
198 "  -G<n>    Number of generations (default: 2)",
199 "  -T<n>    Number of steps in younger generations (default: 2)",
200 "  -c<n>    Use in-place compaction instead of copying in the oldest generation",
201 "           when live data is at least <n>% of the maximum heap size set with",
202 "           -M (default: 30%)",
203 "  -c       Use in-place compaction for all oldest generation collections",
204 "           (the default is to use copying)",
205 "  -w       Use mark-region for the oldest generation (experimental)",
206 #if defined(THREADED_RTS)
207 "  -I<sec>  Perform full GC after <sec> idle time (default: 0.3, 0 == off)",
208 #endif
209 "",
210 "  -t[<file>] One-line GC statistics (if <file> omitted, uses stderr)",
211 "  -s[<file>] Summary  GC statistics (if <file> omitted, uses stderr)",
212 "  -S[<file>] Detailed GC statistics (if <file> omitted, uses stderr)",
213 #ifdef RTS_GTK_FRONTPANEL
214 "  -f       Display front panel (requires X11 & GTK+)",
215 #endif
216 "",
217 "",
218 "  -Z       Don't squeeze out update frames on stack overflow",
219 "  -B       Sound the bell at the start of each garbage collection",
220 #if defined(PROFILING)
221 "",
222 "  -px      Time/allocation profile (XML)  (output file <program>.prof)",
223 "  -p       Time/allocation profile        (output file <program>.prof)",
224 "  -P       More detailed Time/Allocation profile",
225 "  -Pa      Give information about *all* cost centres",
226
227 # if defined(PROFILING)
228 "",
229 "  -hx            Heap residency profile (XML)   (output file <program>.prof)",
230 "  -h<break-down> Heap residency profile (hp2ps) (output file <program>.hp)",
231 "     break-down: c = cost centre stack (default)",
232 "                 m = module",
233 "                 d = closure description",
234 "                 y = type description",
235 "                 r = retainer",
236 "                 b = biography (LAG,DRAG,VOID,USE)",
237 "  A subset of closures may be selected thusly:",
238 "    -hc<cc>,...  specific cost centre(s) (top of stack only)",
239 "    -hC<cc>,...  specific cost centre(s) (anywhere in stack)",
240 "    -hm<mod>...  all cost centres from the specified modules(s)",
241 "    -hd<des>,... closures with specified closure descriptions",
242 "    -hy<typ>...  closures with specified type descriptions",
243 "    -hr<cc>...   closures with specified retainers",
244 "    -hb<bio>...  closures with specified biographies (lag,drag,void,use)",
245 "",
246 "  -R<size>       Set the maximum retainer set size (default: 8)",
247 "", 
248 "  -L<chars>      Maximum length of a cost-centre stack in a heap profile",
249 "                 (default: 25)",
250 "",
251 "  -xt            Include threads (TSOs) in a heap profile",
252 "",
253 "  -xc      Show current cost centre stack on raising an exception",
254 "",
255 # endif
256 #endif /* PROFILING or PAR */
257
258 #ifdef TRACING
259 "",
260 "  -v       Log events to stderr",
261 "  -l       Log events in binary format to the file <program>.eventlog",
262 "  -vt      Include time stamps when tracing events to stderr with -v",
263 "",
264 "  -ls      Log scheduler events",
265 "",
266 #endif
267
268 #if !defined(PROFILING)
269 "",
270 "  -hT      Heap residency profile (output file <program>.hp)",
271 #endif
272 "  -i<sec>  Time between heap samples (seconds, default: 0.1)",
273 "",
274 #if defined(TICKY_TICKY)
275 "  -r<file>  Produce ticky-ticky statistics (with -rstderr for stderr)",
276 "",
277 #endif
278 "  -C<secs>  Context-switch interval in seconds.",
279 "            0 or no argument means switch as often as possible.",
280 "            Default: 0.02 sec; resolution is set by -V below.",
281 "  -V<secs>  Master tick interval in seconds (0 == disable timer).",
282 "            This sets the resolution for -C and the profile timer -i.",
283 "            Default: 0.02 sec.",
284 "",
285 #if defined(DEBUG)
286 "  -Ds  DEBUG: scheduler",
287 "  -Di  DEBUG: interpreter",
288 "  -Dw  DEBUG: weak",
289 "  -DG  DEBUG: gccafs",
290 "  -Dg  DEBUG: gc",
291 "  -Db  DEBUG: block",
292 "  -DS  DEBUG: sanity",
293 "  -Dt  DEBUG: stable",
294 "  -Dp  DEBUG: prof",
295 "  -De  DEBUG: event logging",
296 "  -Da  DEBUG: apply",
297 "  -Dl  DEBUG: linker",
298 "  -Dm  DEBUG: stm",
299 "  -Dz  DEBUG: stack squezing",
300 "  -Dc  DEBUG: program coverage",
301 "  -Dr  DEBUG: sparks",
302 "",
303 "     NOTE: all -D options also enable -v automatically.  Use -l to create a",
304 "     binary event log file instead.",
305 "",
306 #endif /* DEBUG */
307 #if defined(THREADED_RTS) && !defined(NOSMP)
308 "  -N<n>     Use <n> processors (default: 1)",
309 "  -N        Determine the number of processors to use automatically",
310 "  -q1       Use one OS thread for GC (turns off parallel GC)",
311 "  -qg<n>    Use parallel GC only for generations >= <n> (default: 1)",
312 "  -qb       Disable load-balancing in the parallel GC",
313 "  -qa       Use the OS to set thread affinity",
314 "  -qm       Don't automatically migrate threads between CPUs",
315 "  -qw       Migrate a thread to the current CPU when it is woken up",
316 #endif
317 "  --install-signal-handlers=<yes|no>",
318 "            Install signal handlers (default: yes)",
319 #if defined(THREADED_RTS)
320 "  -e<size>  Size of spark pools (default 100)",
321 #endif
322 #if defined(THREADED_RTS)
323 "  -e<n>     Maximum number of outstanding local sparks (default: 4096)",
324 #endif
325 #if defined(x86_64_HOST_ARCH)
326 "  -xm       Base address to mmap memory in the GHCi linker",
327 "            (hex; must be <80000000)",
328 #endif
329 #if defined(USE_PAPI)
330 "  -aX       CPU performance counter measurements using PAPI",
331 "            (use with the -s<file> option).  X is one of:",
332 "",
333 /* "            y - cycles", */
334 "            1 - level 1 cache misses",
335 "            2 - level 2 cache misses",
336 "            b - branch mispredictions",
337 "            s - stalled cycles",
338 "            e - cache miss and branch misprediction events",
339 #endif
340 "",
341 "RTS options may also be specified using the GHCRTS environment variable.",
342 "",
343 "Other RTS options may be available for programs compiled a different way.",
344 "The GHC User's Guide has full details.",
345 "",
346 0
347 };
348
349 STATIC_INLINE rtsBool
350 strequal(const char *a, const char * b)
351 {
352     return(strcmp(a, b) == 0);
353 }
354
355 static void
356 splitRtsFlags(char *s, int *rts_argc, char *rts_argv[])
357 {
358     char *c1, *c2;
359
360     c1 = s;
361     do {
362         while (isspace(*c1)) { c1++; };
363         c2 = c1;
364         while (!isspace(*c2) && *c2 != '\0') { c2++; };
365         
366         if (c1 == c2) { break; }
367         
368         if (*rts_argc < MAX_RTS_ARGS-1) {
369             s = stgMallocBytes(c2-c1+1, "RtsFlags.c:splitRtsFlags()");
370             strncpy(s, c1, c2-c1);
371             s[c2-c1] = '\0';
372             rts_argv[(*rts_argc)++] = s;
373         } else {
374             barf("too many RTS arguments (max %d)", MAX_RTS_ARGS-1);
375         }
376         
377         c1 = c2;
378     } while (*c1 != '\0');
379 }
380     
381 void
382 setupRtsFlags(int *argc, char *argv[], int *rts_argc, char *rts_argv[])
383 {
384     rtsBool error = rtsFalse;
385     I_ mode;
386     I_ arg, total_arg;
387
388     setProgName (argv);
389     total_arg = *argc;
390     arg = 1;
391
392     *argc = 1;
393     *rts_argc = 0;
394
395     // process arguments from the ghc_rts_opts global variable first.
396     // (arguments from the GHCRTS environment variable and the command
397     // line override these).
398     {
399         if (ghc_rts_opts != NULL) {
400             splitRtsFlags(ghc_rts_opts, rts_argc, rts_argv);
401         }
402     }
403
404     // process arguments from the GHCRTS environment variable next
405     // (arguments from the command line override these).
406     {
407         char *ghc_rts = getenv("GHCRTS");
408
409         if (ghc_rts != NULL) {
410             splitRtsFlags(ghc_rts, rts_argc, rts_argv);
411         }
412     }
413
414     // Split arguments (argv) into PGM (argv) and RTS (rts_argv) parts
415     //   argv[0] must be PGM argument -- leave in argv
416
417     for (mode = PGM; arg < total_arg; arg++) {
418         // The '--RTS' argument disables all future +RTS ... -RTS processing.
419         if (strequal("--RTS", argv[arg])) {
420             arg++;
421             break;
422         }
423         // The '--' argument is passed through to the program, but
424         // disables all further +RTS ... -RTS processing.
425         else if (strequal("--", argv[arg])) {
426             break;
427         }
428         else if (strequal("+RTS", argv[arg])) {
429             mode = RTS;
430         }
431         else if (strequal("-RTS", argv[arg])) {
432             mode = PGM;
433         }
434         else if (mode == RTS && *rts_argc < MAX_RTS_ARGS-1) {
435             rts_argv[(*rts_argc)++] = argv[arg];
436         }
437         else if (mode == PGM) {
438             argv[(*argc)++] = argv[arg];
439         }
440         else {
441           barf("too many RTS arguments (max %d)", MAX_RTS_ARGS-1);
442         }
443     }
444     // process remaining program arguments
445     for (; arg < total_arg; arg++) {
446         argv[(*argc)++] = argv[arg];
447     }
448     argv[*argc] = (char *) 0;
449     rts_argv[*rts_argc] = (char *) 0;
450
451     // Process RTS (rts_argv) part: mainly to determine statsfile
452     for (arg = 0; arg < *rts_argc; arg++) {
453         if (rts_argv[arg][0] != '-') {
454             fflush(stdout);
455             errorBelch("unexpected RTS argument: %s", rts_argv[arg]);
456             error = rtsTrue;
457
458         } else {
459             switch(rts_argv[arg][1]) {
460
461               /* process: general args, then PROFILING-only ones, then
462                  CONCURRENT-only, TICKY-only (same order as defined in
463                  RtsFlags.lh); within those groups, mostly in
464                  case-insensitive alphabetical order.  Final group is
465                  x*, which allows for more options.
466               */
467
468 #ifdef TICKY_TICKY
469 # define TICKY_BUILD_ONLY(x) x
470 #else
471 # define TICKY_BUILD_ONLY(x) \
472 errorBelch("not built for: ticky-ticky stats"); \
473 error = rtsTrue;
474 #endif
475
476 #ifdef PROFILING
477 # define PROFILING_BUILD_ONLY(x)   x
478 #else
479 # define PROFILING_BUILD_ONLY(x) \
480 errorBelch("not built for: -prof"); \
481 error = rtsTrue;
482 #endif
483
484 #ifdef TRACING
485 # define TRACING_BUILD_ONLY(x)   x
486 #else
487 # define TRACING_BUILD_ONLY(x) \
488 errorBelch("not built for: -par-prof"); \
489 error = rtsTrue;
490 #endif
491
492 #ifdef THREADED_RTS
493 # define THREADED_BUILD_ONLY(x)      x
494 #else
495 # define THREADED_BUILD_ONLY(x) \
496 errorBelch("not built for: -smp"); \
497 error = rtsTrue;
498 #endif
499
500               /* =========== GENERAL ========================== */
501               case '?':
502                 error = rtsTrue;
503                 break;
504
505               /* This isn't going to allow us to keep related options
506                  together as we add more --* flags. We really need a
507                  proper options parser. */
508               case '-':
509                   if (strequal("install-signal-handlers=yes",
510                                &rts_argv[arg][2])) {
511                       RtsFlags.MiscFlags.install_signal_handlers = rtsTrue;
512                   }
513                   else if (strequal("install-signal-handlers=no",
514                                &rts_argv[arg][2])) {
515                       RtsFlags.MiscFlags.install_signal_handlers = rtsFalse;
516                   }
517                   else if (strequal("machine-readable",
518                                &rts_argv[arg][2])) {
519                       RtsFlags.MiscFlags.machineReadable = rtsTrue;
520                   }
521                   else if (strequal("info",
522                                &rts_argv[arg][2])) {
523                       printRtsInfo();
524                       exit(0);
525                   }
526                   else {
527                       errorBelch("unknown RTS option: %s",rts_argv[arg]);
528                       error = rtsTrue;
529                   }
530                   break;
531               case 'A':
532                 RtsFlags.GcFlags.minAllocAreaSize
533                   = decode(rts_argv[arg]+2) / BLOCK_SIZE;
534                 if (RtsFlags.GcFlags.minAllocAreaSize <= 0) {
535                   bad_option(rts_argv[arg]);
536                 }
537                 break;
538
539 #ifdef USE_PAPI
540               case 'a':
541                 switch(rts_argv[arg][2]) {
542                 case '1':
543                   RtsFlags.PapiFlags.eventType = PAPI_FLAG_CACHE_L1;
544                   break;
545                 case '2':
546                   RtsFlags.PapiFlags.eventType = PAPI_FLAG_CACHE_L2;
547                   break;
548                 case 'b':
549                   RtsFlags.PapiFlags.eventType = PAPI_FLAG_BRANCH;
550                   break;
551                 case 's':
552                   RtsFlags.PapiFlags.eventType = PAPI_FLAG_STALLS;
553                   break;
554                 case 'e':
555                   RtsFlags.PapiFlags.eventType = PAPI_FLAG_CB_EVENTS;
556                   break;
557                 case '+':
558                   if (RtsFlags.PapiFlags.numUserEvents >= MAX_PAPI_USER_EVENTS) {
559                       errorBelch("maximum number of PAPI events reached");
560                       stg_exit(EXIT_FAILURE);
561                   }
562                   RtsFlags.PapiFlags.eventType = PAPI_USER_EVENTS;
563                   RtsFlags.PapiFlags.userEvents[RtsFlags.PapiFlags.numUserEvents++] = rts_argv[arg] + 3;
564                   break;
565                 default:
566                   bad_option( rts_argv[arg] );
567                 }
568                 break;
569 #endif
570
571               case 'B':
572                 RtsFlags.GcFlags.ringBell = rtsTrue;
573                 break;
574
575               case 'c':
576                   if (rts_argv[arg][2] != '\0') {
577                       RtsFlags.GcFlags.compactThreshold =
578                           atof(rts_argv[arg]+2);
579                   } else {
580                       RtsFlags.GcFlags.compact = rtsTrue;
581                   }
582                   break;
583
584               case 'w':
585                 RtsFlags.GcFlags.sweep = rtsTrue;
586                 break;
587
588               case 'F':
589                 RtsFlags.GcFlags.oldGenFactor = atof(rts_argv[arg]+2);
590               
591                 if (RtsFlags.GcFlags.oldGenFactor < 0)
592                   bad_option( rts_argv[arg] );
593                 break;
594               
595 #ifdef DEBUG
596               case 'D':
597               { 
598                   char *c;
599
600                   for (c  = rts_argv[arg] + 2; *c != '\0'; c++) {
601                       switch (*c) {
602                       case 's':
603                           RtsFlags.DebugFlags.scheduler = rtsTrue;
604                           break;
605                       case 'i':
606                           RtsFlags.DebugFlags.interpreter = rtsTrue;
607                           break;
608                       case 'w':
609                           RtsFlags.DebugFlags.weak = rtsTrue;
610                           break;
611                       case 'G':
612                           RtsFlags.DebugFlags.gccafs = rtsTrue;
613                           break;
614                       case 'g':
615                           RtsFlags.DebugFlags.gc = rtsTrue;
616                           break;
617                       case 'b':
618                           RtsFlags.DebugFlags.block_alloc = rtsTrue;
619                           break;
620                       case 'S':
621                           RtsFlags.DebugFlags.sanity = rtsTrue;
622                           break;
623                       case 't':
624                           RtsFlags.DebugFlags.stable = rtsTrue;
625                           break;
626                       case 'p':
627                           RtsFlags.DebugFlags.prof = rtsTrue;
628                           break;
629                       case 'l':
630                           RtsFlags.DebugFlags.linker = rtsTrue;
631                           break;
632                       case 'a':
633                           RtsFlags.DebugFlags.apply = rtsTrue;
634                           break;
635                       case 'm':
636                           RtsFlags.DebugFlags.stm = rtsTrue;
637                           break;
638                       case 'z':
639                           RtsFlags.DebugFlags.squeeze = rtsTrue;
640                           break;
641                       case 'c':
642                           RtsFlags.DebugFlags.hpc = rtsTrue;
643                           break;
644                       case 'r':
645                           RtsFlags.DebugFlags.sparks = rtsTrue;
646                           break;
647                       default:
648                           bad_option( rts_argv[arg] );
649                       }
650                   }
651                   // -Dx also turns on -v.  Use -l to direct trace
652                   // events to the .eventlog file instead.
653                   RtsFlags.TraceFlags.trace_stderr = rtsTrue;
654                   break;
655               }
656 #endif
657
658               case 'K':
659                 RtsFlags.GcFlags.maxStkSize = 
660                   decode(rts_argv[arg]+2) / sizeof(W_);
661
662                 if (RtsFlags.GcFlags.maxStkSize == 0) 
663                   bad_option( rts_argv[arg] );
664                 break;
665
666               case 'k':
667                 RtsFlags.GcFlags.initialStkSize = 
668                   decode(rts_argv[arg]+2) / sizeof(W_);
669
670                 if (RtsFlags.GcFlags.initialStkSize == 0) 
671                   bad_option( rts_argv[arg] );
672                 break;
673
674               case 'M':
675                 RtsFlags.GcFlags.maxHeapSize = 
676                   decode(rts_argv[arg]+2) / BLOCK_SIZE;
677                 /* user give size in *bytes* but "maxHeapSize" is in *blocks* */
678
679                 if (RtsFlags.GcFlags.maxHeapSize <= 0) {
680                   bad_option(rts_argv[arg]);
681                 }
682                 break;
683
684               case 'm':
685                 RtsFlags.GcFlags.pcFreeHeap = atof(rts_argv[arg]+2);
686
687                 if (RtsFlags.GcFlags.pcFreeHeap < 0 || 
688                     RtsFlags.GcFlags.pcFreeHeap > 100)
689                   bad_option( rts_argv[arg] );
690                 break;
691
692               case 'G':
693                 RtsFlags.GcFlags.generations = decode(rts_argv[arg]+2);
694                 if (RtsFlags.GcFlags.generations < 1) {
695                   bad_option(rts_argv[arg]);
696                 }
697                 break;
698
699               case 'T':
700                 RtsFlags.GcFlags.steps = decode(rts_argv[arg]+2);
701                 if (RtsFlags.GcFlags.steps < 1) {
702                   bad_option(rts_argv[arg]);
703                 }
704                 break;
705
706               case 'H':
707                 RtsFlags.GcFlags.heapSizeSuggestion = 
708                   decode(rts_argv[arg]+2) / BLOCK_SIZE;
709                 break;
710
711 #ifdef RTS_GTK_FRONTPANEL
712               case 'f':
713                   RtsFlags.GcFlags.frontpanel = rtsTrue;
714                   break;
715 #endif
716
717               case 'I': /* idle GC delay */
718                 if (rts_argv[arg][2] == '\0') {
719                   /* use default */
720                 } else {
721                     I_ cst; /* tmp */
722
723                     /* Convert to millisecs */
724                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
725                     RtsFlags.GcFlags.idleGCDelayTime = cst;
726                 }
727                 break;
728
729               case 'S':
730                   RtsFlags.GcFlags.giveStats = VERBOSE_GC_STATS;
731                   goto stats;
732
733               case 's':
734                   RtsFlags.GcFlags.giveStats = SUMMARY_GC_STATS;
735                   goto stats;
736
737               case 't':
738                   RtsFlags.GcFlags.giveStats = ONELINE_GC_STATS;
739                   goto stats;
740
741             stats:
742                 { 
743                     int r;
744                     r = open_stats_file(arg, *argc, argv,
745                                         *rts_argc, rts_argv, NULL,
746                                         &RtsFlags.GcFlags.statsFile);
747                     if (r == -1) { error = rtsTrue; }
748                 }
749                 break;
750
751               case 'Z':
752                 RtsFlags.GcFlags.squeezeUpdFrames = rtsFalse;
753                 break;
754
755               /* =========== PROFILING ========================== */
756
757               case 'l':
758 #ifdef TRACING
759                 switch(rts_argv[arg][2]) {
760                 case '\0':
761                   RtsFlags.TraceFlags.trace_stderr = rtsFalse;
762                   break;
763                 case 's':
764                   RtsFlags.TraceFlags.scheduler = rtsTrue;
765                   break;
766                 default:
767                     errorBelch("unknown RTS option: %s",rts_argv[arg]);
768                     error = rtsTrue;
769                     break;
770                 }
771 #else
772                   errorBelch("not built for: -eventlog");
773 #endif
774                   break;
775
776               case 'P': /* detailed cost centre profiling (time/alloc) */
777               case 'p': /* cost centre profiling (time/alloc) */
778                 PROFILING_BUILD_ONLY(
779                 switch (rts_argv[arg][2]) {
780                   case 'x':
781                     RtsFlags.CcFlags.doCostCentres = COST_CENTRES_XML;
782                     break;
783                   case 'a':
784                     RtsFlags.CcFlags.doCostCentres = COST_CENTRES_ALL;
785                     break;
786                   default:
787                       if (rts_argv[arg][1] == 'P') {
788                           RtsFlags.CcFlags.doCostCentres =
789                               COST_CENTRES_VERBOSE;
790                       } else {
791                           RtsFlags.CcFlags.doCostCentres =
792                               COST_CENTRES_SUMMARY;
793                       }
794                       break;
795                 }
796                 ) break;
797
798               case 'R':
799                   PROFILING_BUILD_ONLY(
800                       RtsFlags.ProfFlags.maxRetainerSetSize = atof(rts_argv[arg]+2);
801                   ) break;
802               case 'L':
803                   PROFILING_BUILD_ONLY(
804                       RtsFlags.ProfFlags.ccsLength = atof(rts_argv[arg]+2);
805                       if(RtsFlags.ProfFlags.ccsLength <= 0) {
806                         bad_option(rts_argv[arg]);
807                       }
808                   ) break;
809               case 'h': /* serial heap profile */
810 #if !defined(PROFILING)
811                 switch (rts_argv[arg][2]) {
812                   case '\0':
813                   case 'T':
814                     RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CLOSURE_TYPE;
815                     break;
816                   default:
817                     errorBelch("invalid heap profile option: %s",rts_argv[arg]);
818                     error = rtsTrue;
819                 }
820 #else
821                 PROFILING_BUILD_ONLY(
822                 switch (rts_argv[arg][2]) {
823                 case '\0':
824                 case 'C':
825                 case 'c':
826                 case 'M':
827                 case 'm':
828                 case 'D':
829                 case 'd':
830                 case 'Y':
831                 case 'y':
832                 case 'R':
833                 case 'r':
834                 case 'B':
835                 case 'b':
836                     if (rts_argv[arg][2] != '\0' && rts_argv[arg][3] != '\0') {
837                         {
838                             char *left  = strchr(rts_argv[arg], '{');
839                             char *right = strrchr(rts_argv[arg], '}');
840
841                             // curly braces are optional, for
842                             // backwards compat.
843                             if (left)
844                                 left = left+1;
845                             else
846                                 left = rts_argv[arg] + 3;
847
848                             if (!right)
849                                 right = rts_argv[arg] + strlen(rts_argv[arg]);
850
851                             *right = '\0';
852
853                             switch (rts_argv[arg][2]) {
854                             case 'c': // cost centre label select
855                                 RtsFlags.ProfFlags.ccSelector = left;
856                                 break;
857                             case 'C':
858                                 RtsFlags.ProfFlags.ccsSelector = left;
859                                 break;
860                             case 'M':
861                             case 'm': // cost centre module select
862                                 RtsFlags.ProfFlags.modSelector = left;
863                                 break;
864                             case 'D':
865                             case 'd': // closure descr select 
866                                 RtsFlags.ProfFlags.descrSelector = left;
867                                 break;
868                             case 'Y':
869                             case 'y': // closure type select
870                                 RtsFlags.ProfFlags.typeSelector = left;
871                                 break;
872                             case 'R':
873                             case 'r': // retainer select
874                                 RtsFlags.ProfFlags.retainerSelector = left;
875                                 break;
876                             case 'B':
877                             case 'b': // biography select
878                                 RtsFlags.ProfFlags.bioSelector = left;
879                                 break;
880                             }
881                         }
882                         break;
883                     }
884
885                     if (RtsFlags.ProfFlags.doHeapProfile != 0) {
886                         errorBelch("multiple heap profile options");
887                         error = rtsTrue;
888                         break;
889                     }
890
891                     switch (rts_argv[arg][2]) {
892                     case '\0':
893                     case 'C':
894                     case 'c':
895                         RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CCS;
896                         break;
897                     case 'M':
898                     case 'm':
899                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_MOD;
900                           break;
901                     case 'D':
902                     case 'd':
903                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_DESCR;
904                           break;
905                     case 'Y':
906                     case 'y':
907                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_TYPE;
908                           break;
909                     case 'R':
910                     case 'r':
911                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_RETAINER;
912                           break;
913                     case 'B':
914                     case 'b':
915                           RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_LDV;
916                           break;
917                     }
918                     break;
919                       
920                 default:
921                     errorBelch("invalid heap profile option: %s",rts_argv[arg]);
922                     error = rtsTrue;
923                 }
924                 ) 
925 #endif /* PROFILING */
926                 break;
927
928               case 'i': /* heap sample interval */
929                 if (rts_argv[arg][2] == '\0') {
930                   /* use default */
931                 } else {
932                     I_ cst; /* tmp */
933
934                     /* Convert to milliseconds */
935                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
936                     RtsFlags.ProfFlags.profileInterval = cst;
937                 }
938                 break;
939
940               /* =========== CONCURRENT ========================= */
941               case 'C': /* context switch interval */
942                 if (rts_argv[arg][2] == '\0')
943                     RtsFlags.ConcFlags.ctxtSwitchTime = 0;
944                 else {
945                     I_ cst; /* tmp */
946
947                     /* Convert to milliseconds */
948                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
949                     RtsFlags.ConcFlags.ctxtSwitchTime = cst;
950                 }
951                 break;
952
953               case 'V': /* master tick interval */
954                 if (rts_argv[arg][2] == '\0') {
955                     // turns off ticks completely
956                     RtsFlags.MiscFlags.tickInterval = 0;
957                 } else {
958                     I_ cst; /* tmp */
959
960                     /* Convert to milliseconds */
961                     cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
962                     RtsFlags.MiscFlags.tickInterval = cst;
963                 }
964                 break;
965
966 #if defined(THREADED_RTS) && !defined(NOSMP)
967               case 'N':
968                 THREADED_BUILD_ONLY(
969                 if (rts_argv[arg][2] == '\0') {
970 #if defined(PROFILING)
971                     RtsFlags.ParFlags.nNodes = 1;
972 #else
973                     RtsFlags.ParFlags.nNodes = getNumberOfProcessors();
974 #endif
975                 } else {
976                     RtsFlags.ParFlags.nNodes
977                       = strtol(rts_argv[arg]+2, (char **) NULL, 10);
978                     if (RtsFlags.ParFlags.nNodes <= 0) {
979                       errorBelch("bad value for -N");
980                       error = rtsTrue;
981                     }
982 #if defined(PROFILING)
983                     if (RtsFlags.ParFlags.nNodes > 1) {
984                         errorBelch("bad option %s: only -N1 is supported with profiling", rts_argv[arg]);
985                       error = rtsTrue;
986                     }
987 #endif
988                 }
989                 ) break;
990
991               case 'g':
992                 THREADED_BUILD_ONLY(
993                     switch (rts_argv[arg][2]) {
994                     case '1':
995                         // backwards compat only
996                         RtsFlags.ParFlags.parGcEnabled = rtsFalse;
997                         break;
998                     default:
999                         errorBelch("unknown RTS option: %s",rts_argv[arg]);
1000                         error = rtsTrue;
1001                         break;
1002                     }
1003                     ) break;
1004
1005               case 'q':
1006                     switch (rts_argv[arg][2]) {
1007                     case '\0':
1008                         errorBelch("incomplete RTS option: %s",rts_argv[arg]);
1009                         error = rtsTrue;
1010                         break;
1011                     case '1':
1012                         RtsFlags.ParFlags.parGcEnabled = rtsFalse;
1013                         break;
1014                     case 'g':
1015                         if (rts_argv[arg][3] != '\0') {
1016                             RtsFlags.ParFlags.parGcGen
1017                                 = strtol(rts_argv[arg]+3, (char **) NULL, 10);
1018                         } else {
1019                             errorBelch("bad value for -qg");
1020                             error = rtsTrue;
1021                         }
1022                         break;
1023                     case 'b':
1024                         RtsFlags.ParFlags.parGcLoadBalancing = rtsFalse;
1025                         break;
1026                     case 'a':
1027                         RtsFlags.ParFlags.setAffinity = rtsTrue;
1028                         break;
1029                     case 'm':
1030                         RtsFlags.ParFlags.migrate = rtsFalse;
1031                         break;
1032                     case 'w':
1033                         RtsFlags.ParFlags.wakeupMigrate = rtsTrue;
1034                         break;
1035                     default:
1036                         errorBelch("unknown RTS option: %s",rts_argv[arg]);
1037                         error = rtsTrue;
1038                         break;
1039                     }
1040                     break;
1041 #endif
1042               /* =========== PARALLEL =========================== */
1043               case 'e':
1044                 THREADED_BUILD_ONLY(
1045                 if (rts_argv[arg][2] != '\0') {
1046                     RtsFlags.ParFlags.maxLocalSparks
1047                       = strtol(rts_argv[arg]+2, (char **) NULL, 10);
1048                     if (RtsFlags.ParFlags.maxLocalSparks <= 0) {
1049                       errorBelch("bad value for -e");
1050                       error = rtsTrue;
1051                     }
1052                 }
1053                 ) break;
1054
1055               /* =========== TICKY ============================== */
1056
1057               case 'r': /* Basic profiling stats */
1058                 TICKY_BUILD_ONLY(
1059
1060                 RtsFlags.TickyFlags.showTickyStats = rtsTrue;
1061
1062                 { 
1063                     int r;
1064                     r = open_stats_file(arg, *argc, argv,
1065                                         *rts_argc, rts_argv, TICKY_FILENAME_FMT,
1066                                         &RtsFlags.TickyFlags.tickyFile);
1067                     if (r == -1) { error = rtsTrue; }
1068                 }
1069                 ) break;
1070
1071               /* =========== TRACING ---------=================== */
1072
1073               case 'v':
1074                 switch(rts_argv[arg][2]) {
1075 #ifdef TRACING
1076                 case '\0':
1077                     RtsFlags.TraceFlags.trace_stderr = rtsTrue;
1078                     break;
1079                 case 't':
1080                     RtsFlags.TraceFlags.timestamp = rtsTrue;
1081                     break;
1082 #endif
1083                 case 's':
1084                 case 'g':
1085                     // ignored for backwards-compat
1086                     break;
1087                 default:
1088                     errorBelch("unknown RTS option: %s",rts_argv[arg]);
1089                     error = rtsTrue;
1090                     break;
1091                 }
1092                 break;
1093
1094               /* =========== EXTENDED OPTIONS =================== */
1095
1096               case 'x': /* Extend the argument space */
1097                 switch(rts_argv[arg][2]) {
1098                   case '\0':
1099                     errorBelch("incomplete RTS option: %s",rts_argv[arg]);
1100                     error = rtsTrue;
1101                     break;
1102
1103                 case 'b': /* heapBase in hex; undocumented */
1104                     if (rts_argv[arg][3] != '\0') {
1105                         RtsFlags.GcFlags.heapBase
1106                             = strtol(rts_argv[arg]+3, (char **) NULL, 16);
1107                     } else {
1108                         errorBelch("-xb: requires argument");
1109                         error = rtsTrue;
1110                     }
1111                     break;
1112
1113 #if defined(x86_64_HOST_ARCH)
1114                 case 'm': /* linkerMemBase */
1115                     if (rts_argv[arg][3] != '\0') {
1116                         RtsFlags.MiscFlags.linkerMemBase
1117                             = strtol(rts_argv[arg]+3, (char **) NULL, 16);
1118                         if (RtsFlags.MiscFlags.linkerMemBase > 0x80000000) {
1119                             errorBelch("-xm: value must be <80000000");
1120                             error = rtsTrue;
1121                         }
1122                     } else {
1123                         RtsFlags.MiscFlags.linkerMemBase = 0;
1124                     }
1125                     break;
1126 #endif
1127
1128                 case 'c': /* Debugging tool: show current cost centre on an exception */
1129                     PROFILING_BUILD_ONLY(
1130                         RtsFlags.ProfFlags.showCCSOnException = rtsTrue;
1131                         );
1132                     break;
1133
1134                 case 't':  /* Include memory used by TSOs in a heap profile */
1135                     PROFILING_BUILD_ONLY(
1136                         RtsFlags.ProfFlags.includeTSOs = rtsTrue;
1137                         );
1138                     break;
1139
1140                   /* The option prefix '-xx' is reserved for future extension.  KSW 1999-11. */
1141
1142                   default:
1143                     errorBelch("unknown RTS option: %s",rts_argv[arg]);
1144                     error = rtsTrue;
1145                     break;
1146                 }
1147                 break;  /* defensive programming */
1148
1149               /* =========== OH DEAR ============================ */
1150               default:
1151                 errorBelch("unknown RTS option: %s",rts_argv[arg]);
1152                 error = rtsTrue;
1153                 break;
1154             }
1155         }
1156     }
1157
1158     if (RtsFlags.MiscFlags.tickInterval < 0) {
1159         RtsFlags.MiscFlags.tickInterval = 50;
1160     }
1161
1162     // If the master timer is disabled, turn off the other timers.
1163     if (RtsFlags.MiscFlags.tickInterval == 0) {
1164         RtsFlags.ConcFlags.ctxtSwitchTime  = 0;
1165         RtsFlags.GcFlags.idleGCDelayTime   = 0;
1166         RtsFlags.ProfFlags.profileInterval = 0;
1167     }
1168
1169     // Determine what tick interval we should use for the RTS timer
1170     // by taking the shortest of the various intervals that we need to
1171     // monitor.
1172     if (RtsFlags.ConcFlags.ctxtSwitchTime > 0) {
1173         RtsFlags.MiscFlags.tickInterval =
1174             stg_min(RtsFlags.ConcFlags.ctxtSwitchTime,
1175                     RtsFlags.MiscFlags.tickInterval);
1176     }
1177
1178     if (RtsFlags.GcFlags.idleGCDelayTime > 0) {
1179         RtsFlags.MiscFlags.tickInterval =
1180             stg_min(RtsFlags.GcFlags.idleGCDelayTime,
1181                     RtsFlags.MiscFlags.tickInterval);
1182     }
1183
1184     if (RtsFlags.ProfFlags.profileInterval > 0) {
1185         RtsFlags.MiscFlags.tickInterval =
1186             stg_min(RtsFlags.ProfFlags.profileInterval,
1187                     RtsFlags.MiscFlags.tickInterval);
1188     }
1189
1190     if (RtsFlags.ConcFlags.ctxtSwitchTime > 0) {
1191         RtsFlags.ConcFlags.ctxtSwitchTicks =
1192             RtsFlags.ConcFlags.ctxtSwitchTime /
1193             RtsFlags.MiscFlags.tickInterval;
1194     } else {
1195         RtsFlags.ConcFlags.ctxtSwitchTicks = 0;
1196     }
1197
1198     if (RtsFlags.ProfFlags.profileInterval > 0) {
1199         RtsFlags.ProfFlags.profileIntervalTicks =
1200             RtsFlags.ProfFlags.profileInterval / 
1201             RtsFlags.MiscFlags.tickInterval;
1202     } else {
1203         RtsFlags.ProfFlags.profileIntervalTicks = 0;
1204     }
1205
1206     if (error) {
1207         const char **p;
1208
1209         fflush(stdout);
1210         for (p = usage_text; *p; p++)
1211             errorBelch("%s", *p);
1212         stg_exit(EXIT_FAILURE);
1213     }
1214 }
1215
1216
1217 static void
1218 stats_fprintf(FILE *f, char *s, ...)
1219 {
1220     va_list ap;
1221     va_start(ap,s);
1222     if (f == NULL) {
1223         vdebugBelch(s, ap);
1224     } else {
1225         vfprintf(f, s, ap);
1226     }
1227     va_end(ap);
1228 }
1229
1230 static int              /* return -1 on error */
1231 open_stats_file (
1232     I_ arg,
1233     int argc, char *argv[],
1234     int rts_argc, char *rts_argv[],
1235     const char *FILENAME_FMT,
1236     FILE **file_ret)
1237 {
1238     FILE *f = NULL;
1239
1240     if (strequal(rts_argv[arg]+2, "stderr")
1241         || (FILENAME_FMT == NULL && rts_argv[arg][2] == '\0')) {
1242         f = NULL; /* NULL means use debugBelch */
1243     } else {
1244         if (rts_argv[arg][2] != '\0') {  /* stats file specified */
1245             f = fopen(rts_argv[arg]+2,"w");
1246         } else {
1247             char stats_filename[STATS_FILENAME_MAXLEN]; /* default <program>.<ext> */
1248             sprintf(stats_filename, FILENAME_FMT, argv[0]);
1249             f = fopen(stats_filename,"w");
1250         }
1251         if (f == NULL) {
1252             errorBelch("Can't open stats file %s\n", rts_argv[arg]+2);
1253             return -1;
1254         }
1255     }
1256     *file_ret = f;
1257
1258     {
1259         /* Write argv and rtsv into start of stats file */
1260         int count;
1261         for(count = 0; count < argc; count++) {
1262             stats_fprintf(f, "%s ", argv[count]);
1263         }
1264         stats_fprintf(f, "+RTS ");
1265         for(count = 0; count < rts_argc; count++)
1266             stats_fprintf(f, "%s ", rts_argv[count]);
1267         stats_fprintf(f, "\n");
1268     }
1269     return 0;
1270 }
1271
1272
1273
1274 static I_
1275 decode(const char *s)
1276 {
1277     I_ c;
1278     StgDouble m;
1279
1280     if (!*s)
1281         return 0;
1282
1283     m = atof(s);
1284     c = s[strlen(s)-1];
1285
1286     if (c == 'g' || c == 'G')
1287         m *= 1000*1000*1000;    /* UNchecked! */
1288     else if (c == 'm' || c == 'M')
1289         m *= 1000*1000;                 /* We do not use powers of 2 (1024) */
1290     else if (c == 'k' || c == 'K')      /* to avoid possible bad effects on */
1291         m *= 1000;                      /* a direct-mapped cache.           */ 
1292     else if (c == 'w' || c == 'W')
1293         m *= sizeof(W_);
1294
1295     return (I_)m;
1296 }
1297
1298 static void GNU_ATTRIBUTE(__noreturn__)
1299 bad_option(const char *s)
1300 {
1301   errorBelch("bad RTS option: %s", s);
1302   stg_exit(EXIT_FAILURE);
1303 }
1304
1305 /* -----------------------------------------------------------------------------
1306    Getting/Setting the program's arguments.
1307
1308    These are used by System.Environment, and parts of the RTS.
1309    -------------------------------------------------------------------------- */
1310
1311 void
1312 setProgName(char *argv[])
1313 {
1314     /* Remove directory from argv[0] -- default files in current directory */
1315 #if !defined(mingw32_HOST_OS)
1316     char *last_slash;
1317     if ( (last_slash = (char *) strrchr(argv[0], '/')) != NULL ) {
1318         prog_name = last_slash+1;
1319    } else {
1320         prog_name = argv[0];
1321    }
1322 #else
1323     char* last_slash = argv[0] + (strlen(argv[0]) - 1);
1324     while ( last_slash > argv[0] ) {
1325         if ( *last_slash == '/' || *last_slash == '\\' ) {
1326             prog_name = last_slash+1;
1327             return;
1328         }
1329         last_slash--;
1330     }
1331     prog_name = argv[0];
1332 #endif
1333 }
1334
1335 void
1336 getProgArgv(int *argc, char **argv[])
1337 {
1338     if (argc) { *argc = prog_argc; }
1339     if (argv) { *argv = prog_argv; }
1340 }
1341
1342 void
1343 setProgArgv(int argc, char *argv[])
1344 {
1345    /* Usually this is done by startupHaskell, so we don't need to call this. 
1346       However, sometimes Hugs wants to change the arguments which Haskell
1347       getArgs >>= ... will be fed.  So you can do that by calling here
1348       _after_ calling startupHaskell.
1349    */
1350    prog_argc = argc;
1351    prog_argv = argv;
1352    setProgName(prog_argv);
1353 }
1354
1355 /* These functions record and recall the full arguments, including the
1356    +RTS ... -RTS options. The reason for adding them was so that the
1357    ghc-inplace program can pass /all/ the arguments on to the real ghc. */
1358 void
1359 getFullProgArgv(int *argc, char **argv[])
1360 {
1361     if (argc) { *argc = full_prog_argc; }
1362     if (argv) { *argv = full_prog_argv; }
1363 }
1364
1365 void
1366 setFullProgArgv(int argc, char *argv[])
1367 {
1368     int i;
1369     full_prog_argc = argc;
1370     full_prog_argv = stgCallocBytes(argc + 1, sizeof (char *),
1371                                     "setFullProgArgv 1");
1372     for (i = 0; i < argc; i++) {
1373         full_prog_argv[i] = stgMallocBytes(strlen(argv[i]) + 1,
1374                                            "setFullProgArgv 2");
1375         strcpy(full_prog_argv[i], argv[i]);
1376     }
1377     full_prog_argv[argc] = NULL;
1378 }
1379