RtsFlags.c 54.8 KB
Newer Older
1
/* -----------------------------------------------------------------------------
2 3
 *
 * (c) The AQUA Project, Glasgow University, 1994-1997
Simon Marlow's avatar
Simon Marlow committed
4
 * (c) The GHC Team, 1998-2006
5 6 7 8 9
 *
 * Functions for parsing the argument list.
 *
 * ---------------------------------------------------------------------------*/

10
#include "PosixSource.h"
11
#include "Rts.h"
Simon Marlow's avatar
Simon Marlow committed
12

13
#include "RtsUtils.h"
14
#include "Profiling.h"
15
#include "RtsFlags.h"
16

17 18
#ifdef HAVE_CTYPE_H
#include <ctype.h>
19 20
#endif

21 22
#include <string.h>

23 24 25 26 27 28 29 30
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

31 32
// Flag Structure
RTS_FLAGS RtsFlags;
33 34 35 36

/*
 * Split argument lists
 */
sof's avatar
sof committed
37
int     prog_argc = 0;    /* an "int" so as to match normal "argc" */
38
char  **prog_argv = NULL;
39 40
int     full_prog_argc = 0;    /* an "int" so as to match normal "argc" */
char  **full_prog_argv = NULL;
sof's avatar
sof committed
41
char   *prog_name = NULL; /* 'basename' of prog_argv[0] */
42
int     rts_argc = 0;  /* ditto */
43
char  **rts_argv = NULL;
44
int     rts_argv_size = 0;
45 46 47 48 49 50 51 52
#if defined(mingw32_HOST_OS)
// On Windows, we want to use GetCommandLineW rather than argc/argv,
// but we need to mutate the command line arguments for withProgName and
// friends. The System.Environment module achieves that using this bit of
// shared state:
int       win32_prog_argc = 0;
wchar_t **win32_prog_argv = NULL;
#endif
53 54 55 56 57 58 59 60 61 62 63

/*
 * constants, used later 
 */
#define RTS 1
#define PGM 0

/* -----------------------------------------------------------------------------
   Static function decls
   -------------------------------------------------------------------------- */

64 65 66 67 68 69 70 71 72 73 74 75 76
static void procRtsOpts      (int rts_argc0, RtsOptsEnabledEnum enabled);

static void normaliseRtsOpts (void);

static void initStatsFile    (FILE *f);

static int  openStatsFile    (char *filename, const char *FILENAME_FMT,
                              FILE **file_ret);

static StgWord64 decodeSize  (const char *flag, nat offset,
                              StgWord64 min, StgWord64 max);

static void bad_option       (const char *s);
77

78 79 80
#ifdef TRACING
static void read_trace_flags(char *arg);
#endif
81

82 83
static void errorUsage      (void) GNU_ATTRIBUTE(__noreturn__);

84 85 86 87
static char *  copyArg  (char *arg);
static char ** copyArgv (int argc, char *argv[]);
static void    freeArgv (int argc, char *argv[]);

88 89 90 91 92 93 94 95 96
/* -----------------------------------------------------------------------------
 * Command-line option parsing routines.
 * ---------------------------------------------------------------------------*/

void initRtsFlagsDefaults(void)
{
    RtsFlags.GcFlags.statsFile		= NULL;
    RtsFlags.GcFlags.giveStats		= NO_GC_STATS;

97
    RtsFlags.GcFlags.maxStkSize		= (8 * 1024 * 1024) / sizeof(W_);
98
    RtsFlags.GcFlags.initialStkSize	= 1024 / sizeof(W_);
99 100
    RtsFlags.GcFlags.stkChunkSize       = (32 * 1024) / sizeof(W_);
    RtsFlags.GcFlags.stkChunkBufferSize = (1 * 1024) / sizeof(W_);
101

102
    RtsFlags.GcFlags.minAllocAreaSize   = (512 * 1024)        / BLOCK_SIZE;
103
    RtsFlags.GcFlags.minOldGenSize      = (1024 * 1024)       / BLOCK_SIZE;
104
    RtsFlags.GcFlags.maxHeapSize	= 0;    /* off by default */
105
    RtsFlags.GcFlags.heapSizeSuggestion	= 0;    /* none */
106
    RtsFlags.GcFlags.heapSizeSuggestionAuto = rtsFalse;
107
    RtsFlags.GcFlags.pcFreeHeap		= 3;	/* 3% */
108
    RtsFlags.GcFlags.oldGenFactor       = 2;
109
    RtsFlags.GcFlags.generations        = 2;
110
    RtsFlags.GcFlags.squeezeUpdFrames	= rtsTrue;
111
    RtsFlags.GcFlags.compact            = rtsFalse;
112
    RtsFlags.GcFlags.compactThreshold   = 30.0;
113
    RtsFlags.GcFlags.sweep              = rtsFalse;
114 115 116
#ifdef RTS_GTK_FRONTPANEL
    RtsFlags.GcFlags.frontpanel         = rtsFalse;
#endif
Simon Marlow's avatar
Simon Marlow committed
117
    RtsFlags.GcFlags.idleGCDelayTime    = USToTime(300000); // 300ms
118

119 120 121 122 123 124 125 126 127 128 129 130
#if osf3_HOST_OS
/* ToDo: Perhaps by adjusting this value we can make linking without
 * -static work (i.e., not generate a core-dumping executable)? */
# if SIZEOF_VOID_P == 8
    RtsFlags.GcFlags.heapBase           = 0x180000000L;
# else
#  error I have no idea where to begin the heap on a non-64-bit osf3 machine.
# endif
#else
    RtsFlags.GcFlags.heapBase           = 0;   /* means don't care */
#endif

131 132
#ifdef DEBUG
    RtsFlags.DebugFlags.scheduler	= rtsFalse;
133
    RtsFlags.DebugFlags.interpreter	= rtsFalse;
134 135 136 137 138 139
    RtsFlags.DebugFlags.weak		= rtsFalse;
    RtsFlags.DebugFlags.gccafs		= rtsFalse;
    RtsFlags.DebugFlags.gc		= rtsFalse;
    RtsFlags.DebugFlags.block_alloc	= rtsFalse;
    RtsFlags.DebugFlags.sanity		= rtsFalse;
    RtsFlags.DebugFlags.stable		= rtsFalse;
140
    RtsFlags.DebugFlags.stm             = rtsFalse;
141
    RtsFlags.DebugFlags.prof		= rtsFalse;
142
    RtsFlags.DebugFlags.apply		= rtsFalse;
143
    RtsFlags.DebugFlags.linker		= rtsFalse;
144
    RtsFlags.DebugFlags.squeeze		= rtsFalse;
145
    RtsFlags.DebugFlags.hpc		= rtsFalse;
146
    RtsFlags.DebugFlags.sparks		= rtsFalse;
147 148
#endif

Simon Marlow's avatar
Simon Marlow committed
149
#if defined(PROFILING)
150
    RtsFlags.CcFlags.doCostCentres	= 0;
Simon Marlow's avatar
Simon Marlow committed
151
#endif /* PROFILING */
152

153
    RtsFlags.ProfFlags.doHeapProfile      = rtsFalse;
Simon Marlow's avatar
Simon Marlow committed
154
    RtsFlags.ProfFlags. heapProfileInterval = USToTime(100000); // 100ms
155 156

#ifdef PROFILING
157
    RtsFlags.ProfFlags.includeTSOs        = rtsFalse;
158
    RtsFlags.ProfFlags.showCCSOnException = rtsFalse;
159
    RtsFlags.ProfFlags.maxRetainerSetSize = 8;
ravi@bluespec.com's avatar
ravi@bluespec.com committed
160
    RtsFlags.ProfFlags.ccsLength          = 25;
161 162 163 164
    RtsFlags.ProfFlags.modSelector        = NULL;
    RtsFlags.ProfFlags.descrSelector      = NULL;
    RtsFlags.ProfFlags.typeSelector       = NULL;
    RtsFlags.ProfFlags.ccSelector         = NULL;
165
    RtsFlags.ProfFlags.ccsSelector        = NULL;
166 167
    RtsFlags.ProfFlags.retainerSelector   = NULL;
    RtsFlags.ProfFlags.bioSelector        = NULL;
168 169
#endif

170
#ifdef TRACING
171
    RtsFlags.TraceFlags.tracing       = TRACE_NONE;
172 173
    RtsFlags.TraceFlags.timestamp     = rtsFalse;
    RtsFlags.TraceFlags.scheduler     = rtsFalse;
174
    RtsFlags.TraceFlags.gc            = rtsFalse;
175 176
    RtsFlags.TraceFlags.sparks_sampled= rtsFalse;
    RtsFlags.TraceFlags.sparks_full   = rtsFalse;
177
    RtsFlags.TraceFlags.user          = rtsFalse;
Simon Marlow's avatar
Simon Marlow committed
178 179
#endif

Simon Marlow's avatar
Simon Marlow committed
180 181 182 183 184 185 186
#ifdef PROFILING
    // When profiling we want a lot more ticks
    RtsFlags.MiscFlags.tickInterval     = USToTime(1000);  // 1ms
#else
    RtsFlags.MiscFlags.tickInterval     = DEFAULT_TICK_INTERVAL;
#endif
    RtsFlags.ConcFlags.ctxtSwitchTime   = USToTime(20000); // 20ms
187

188
    RtsFlags.MiscFlags.install_signal_handlers = rtsTrue;
Ian Lynagh's avatar
Ian Lynagh committed
189
    RtsFlags.MiscFlags.machineReadable = rtsFalse;
190
    RtsFlags.MiscFlags.linkerMemBase    = 0;
191

192
#ifdef THREADED_RTS
193
    RtsFlags.ParFlags.nNodes	        = 1;
194
    RtsFlags.ParFlags.migrate           = rtsTrue;
195
    RtsFlags.ParFlags.parGcEnabled      = 1;
196 197 198
    RtsFlags.ParFlags.parGcGen          = 0;
    RtsFlags.ParFlags.parGcLoadBalancingEnabled = rtsTrue;
    RtsFlags.ParFlags.parGcLoadBalancingGen = 1;
199
    RtsFlags.ParFlags.parGcNoSyncWithIdle   = 0;
200
    RtsFlags.ParFlags.setAffinity       = 0;
201
#endif
202

Simon Marlow's avatar
Simon Marlow committed
203
#if defined(THREADED_RTS)
204
    RtsFlags.ParFlags.maxLocalSparks	= 4096;
Simon Marlow's avatar
Simon Marlow committed
205
#endif /* THREADED_RTS */
206 207

#ifdef TICKY_TICKY
208 209
    RtsFlags.TickyFlags.showTickyStats	 = rtsFalse;
    RtsFlags.TickyFlags.tickyFile	 = NULL;
210
#endif
Simon Marlow's avatar
Simon Marlow committed
211

212
#ifdef USE_PAPI
213 214
    /* By default no special measurements taken */
    RtsFlags.PapiFlags.eventType        = 0;
215
    RtsFlags.PapiFlags.numUserEvents    = 0;
216
#endif
217 218 219 220 221 222 223 224 225 226 227 228 229 230
}

static const char *
usage_text[] = {
"",
"Usage: <prog> <args> [+RTS <rtsopts> | -RTS <args>] ... --RTS <args>",
"",
"   +RTS    Indicates run time system options follow",
"   -RTS    Indicates program arguments follow",
"  --RTS    Indicates that ALL subsequent arguments will be given to the",
"           program (including any of these RTS flags)",
"",
"The following run time system options are available:",
"",
231
"  -?       Prints this message and exits; the program is not executed",
232
"  --info   Print information about the RTS used by this program",
233
"",
234
"  -K<size> Sets the maximum stack size (default 8M)  Egs: -K32k   -K512k",
235 236 237
"  -ki<size> Sets the initial thread stack size (default 1k)  Egs: -ki4k -ki2m",
"  -kc<size> Sets the stack chunk size (default 32k)",
"  -kb<size> Sets the stack chunk buffer size (default 1k)",
238
"",
239
"  -A<size> Sets the minimum allocation area size (default 512k) Egs: -A1m -A10k",
240
"  -M<size> Sets the maximum heap size (default unlimited)  Egs: -M256k -M1G",
241
"  -H<size> Sets the minimum heap size (default 0M)   Egs: -H24m  -H1G",
242
"  -m<n>    Minimum % of heap which must be available (default 3%)",
243
"  -G<n>    Number of generations (default: 2)",
244 245 246 247 248
"  -c<n>    Use in-place compaction instead of copying in the oldest generation",
"           when live data is at least <n>% of the maximum heap size set with",
"           -M (default: 30%)",
"  -c       Use in-place compaction for all oldest generation collections",
"           (the default is to use copying)",
249
"  -w       Use mark-region for the oldest generation (experimental)",
250
#if defined(THREADED_RTS)
251 252
"  -I<sec>  Perform full GC after <sec> idle time (default: 0.3, 0 == off)",
#endif
253
"",
254
"  -T         Collect GC statistics (useful for in-program statistics access)",
255 256 257
"  -t[<file>] One-line GC statistics (if <file> omitted, uses stderr)",
"  -s[<file>] Summary  GC statistics (if <file> omitted, uses stderr)",
"  -S[<file>] Detailed GC statistics (if <file> omitted, uses stderr)",
258 259 260
#ifdef RTS_GTK_FRONTPANEL
"  -f       Display front panel (requires X11 & GTK+)",
#endif
261 262 263 264
"",
"",
"  -Z       Don't squeeze out update frames on stack overflow",
"  -B       Sound the bell at the start of each garbage collection",
Simon Marlow's avatar
Simon Marlow committed
265
#if defined(PROFILING)
266
"",
andy's avatar
andy committed
267 268 269
"  -p       Time/allocation profile        (output file <program>.prof)",
"  -P       More detailed Time/Allocation profile",
"  -Pa      Give information about *all* cost centres",
270

271 272
# if defined(PROFILING)
"",
273 274 275 276 277 278 279
"  -h<break-down> Heap residency profile (hp2ps) (output file <program>.hp)",
"     break-down: c = cost centre stack (default)",
"                 m = module",
"                 d = closure description",
"                 y = type description",
"                 r = retainer",
"                 b = biography (LAG,DRAG,VOID,USE)",
280
"  A subset of closures may be selected thusly:",
281 282
"    -hc<cc>,...  specific cost centre(s) (top of stack only)",
"    -hC<cc>,...  specific cost centre(s) (anywhere in stack)",
283 284 285 286 287
"    -hm<mod>...  all cost centres from the specified modules(s)",
"    -hd<des>,... closures with specified closure descriptions",
"    -hy<typ>...  closures with specified type descriptions",
"    -hr<cc>...   closures with specified retainers",
"    -hb<bio>...  closures with specified biographies (lag,drag,void,use)",
288 289
"",
"  -R<size>       Set the maximum retainer set size (default: 8)",
ravi@bluespec.com's avatar
ravi@bluespec.com committed
290 291 292
"", 
"  -L<chars>      Maximum length of a cost-centre stack in a heap profile",
"                 (default: 25)",
293
"",
294 295
"  -xt            Include threads (TSOs) in a heap profile",
"",
296
"  -xc      Show current cost centre stack on raising an exception",
297 298
# endif
#endif /* PROFILING or PAR */
Simon Marlow's avatar
Simon Marlow committed
299

300
#ifdef TRACING
Simon Marlow's avatar
Simon Marlow committed
301
"",
302 303 304 305 306 307
"  -l[flags]  Log events in binary format to the file <program>.eventlog",
#  ifdef DEBUG
"  -v[flags]  Log events to stderr",
#  endif
"             where [flags] can contain:",
"                s    scheduler events",
308
"                g    GC events",
309 310
"                p    par spark events (sampled)",
"                f    par spark events (full detail)",
311 312
"                u    user events (emitted from Haskell code)",
"                a    all event classes above",
313 314 315
#  ifdef DEBUG
"                t    add time stamps (only useful with -v)",
#  endif
316
"               -x    disable an event class, for any flag above",
317
"             the initial enabled event classes are 'sgpu'",
Simon Marlow's avatar
Simon Marlow committed
318 319
#endif

320
#if !defined(PROFILING)
321
"",
Simon Marlow's avatar
Simon Marlow committed
322
"  -h       Heap residency profile (output file <program>.hp)",
323
#endif
Simon Marlow's avatar
Simon Marlow committed
324
"  -i<sec>  Time between heap profile samples (seconds, default: 0.1)",
325 326
"",
#if defined(TICKY_TICKY)
327
"  -r<file>  Produce ticky-ticky statistics (with -rstderr for stderr)",
328 329
"",
#endif
330 331 332
"  -C<secs>  Context-switch interval in seconds.",
"            0 or no argument means switch as often as possible.",
"            Default: 0.02 sec.",
Simon Marlow's avatar
Simon Marlow committed
333 334 335 336 337 338 339 340
"  -V<secs>  Master tick interval in seconds (0 == disable timer).",
"            This sets the resolution for -C and the heap profile timer -i,",
"            and is the frequence of time profile samples.",
#ifdef PROFILING
"            Default: 0.001 sec.",
#else
"            Default: 0.01 sec.",
#endif
341 342 343
"",
#if defined(DEBUG)
"  -Ds  DEBUG: scheduler",
344
"  -Di  DEBUG: interpreter",
345 346 347 348 349 350 351
"  -Dw  DEBUG: weak",
"  -DG  DEBUG: gccafs",
"  -Dg  DEBUG: gc",
"  -Db  DEBUG: block",
"  -DS  DEBUG: sanity",
"  -Dt  DEBUG: stable",
"  -Dp  DEBUG: prof",
352
"  -Da  DEBUG: apply",
353
"  -Dl  DEBUG: linker",
354
"  -Dm  DEBUG: stm",
Simon Marlow's avatar
Simon Marlow committed
355
"  -Dz  DEBUG: stack squeezing",
356
"  -Dc  DEBUG: program coverage",
357 358
"  -Dr  DEBUG: sparks",
"",
359
"     NOTE: DEBUG events are sent to stderr by default; add -l to create a",
360
"     binary event log file instead.",
361
"",
362
#endif /* DEBUG */
363
#if defined(THREADED_RTS) && !defined(NOSMP)
364 365
"  -N<n>     Use <n> processors (default: 1)",
"  -N        Determine the number of processors to use automatically",
366 367 368 369 370
"  -qg[<n>]  Use parallel GC only for generations >= <n>",
"            (default: 0, -qg alone turns off parallel GC)",
"  -qb[<n>]  Use load-balancing in the parallel GC only for generations >= <n>",
"            (default: 1, -qb alone turns off load-balancing)",
"  -qa       Use the OS to set thread affinity (experimental)",
371
"  -qm       Don't automatically migrate threads between CPUs",
372 373 374
"  -qi<n>    If a processor has been idle for the last <n> GCs, do not",
"            wake it up for a non-load-balancing parallel GC.",
"            (0 disables,  default: 0)",
375
#endif
376 377
"  --install-signal-handlers=<yes|no>",
"            Install signal handlers (default: yes)",
Simon Marlow's avatar
Simon Marlow committed
378
#if defined(THREADED_RTS)
379 380
"  -e<n>     Maximum number of outstanding local sparks (default: 4096)",
#endif
381 382 383 384
#if defined(x86_64_HOST_ARCH)
"  -xm       Base address to mmap memory in the GHCi linker",
"            (hex; must be <80000000)",
#endif
385
#if defined(USE_PAPI)
386 387
"  -aX       CPU performance counter measurements using PAPI",
"            (use with the -s<file> option).  X is one of:",
388 389 390 391 392 393
"",
/* "            y - cycles", */
"            1 - level 1 cache misses",
"            2 - level 2 cache misses",
"            b - branch mispredictions",
"            s - stalled cycles",
394
"            e - cache miss and branch misprediction events",
395 396
"            +PAPI_EVENT   - collect papi preset event PAPI_EVENT",
"            #NATIVE_EVENT - collect native event NATIVE_EVENT (in hex)",
397
#endif
398
"",
399 400
"RTS options may also be specified using the GHCRTS environment variable.",
"",
401 402 403 404 405 406
"Other RTS options may be available for programs compiled a different way.",
"The GHC User's Guide has full details.",
"",
0
};

sof's avatar
sof committed
407
STATIC_INLINE rtsBool
408 409 410 411 412
strequal(const char *a, const char * b)
{
    return(strcmp(a, b) == 0);
}

413 414 415 416 417 418 419 420 421 422 423 424 425
// We can't predict up front how much space we'll need for rts_argv,
// because it involves parsing ghc_rts_opts and GHCRTS, so we
// expand it on demand.
static void appendRtsArg (char *arg)
{
    if (rts_argc == rts_argv_size) {
        rts_argv_size *= 2;
        rts_argv = stgReallocBytes(rts_argv, rts_argv_size * sizeof (char *),
                                   "RtsFlags.c:appendRtsArg");
    }
    rts_argv[rts_argc++] = arg;
}

426
static void splitRtsFlags(const char *s)
427
{
428 429
    const char *c1, *c2;
    char *t;
430 431 432 433 434 435 436 437 438

    c1 = s;
    do {
	while (isspace(*c1)) { c1++; };
	c2 = c1;
	while (!isspace(*c2) && *c2 != '\0') { c2++; };
	
	if (c1 == c2) { break; }
	
439 440 441
        t = stgMallocBytes(c2-c1+1, "RtsFlags.c:splitRtsFlags()");
        strncpy(t, c1, c2-c1);
        t[c2-c1] = '\0';
442
        appendRtsArg(t);
443

444 445 446 447
	c1 = c2;
    } while (*c1 != '\0');
}
    
448 449 450 451 452 453 454
/* -----------------------------------------------------------------------------
   Parse the command line arguments, collecting options for the RTS.

   On return:
     - argv[] is *modified*, any RTS options have been stripped out
     - *argc  contains the new count of arguments in argv[]

455
     - rts_argv[]  (global) contains a copy of the collected RTS args
456 457
     - rts_argc    (global) contains the count of args in rts_argv

458
     - prog_argv[] (global) contains a copy of the non-RTS args (== argv)
459 460
     - prog_argc   (global) contains the count of args in prog_argv

461
     - prog_name   (global) contains the basename of prog_argv[0]
462 463 464

  -------------------------------------------------------------------------- */

465 466 467
void setupRtsFlags (int *argc, char *argv[],
                    RtsOptsEnabledEnum rtsOptsEnabled,
                    const char *ghc_rts_opts)
468
{
469 470 471
    nat mode;
    nat total_arg;
    nat arg, rts_argc0;
472

473
    setProgName (argv);
474 475 476 477
    total_arg = *argc;
    arg = 1;

    *argc = 1;
478 479
    rts_argc = 0;

480 481
    rts_argv_size = total_arg + 1;
    rts_argv = stgMallocBytes(rts_argv_size * sizeof (char *), "setupRtsFlags");
482

483
    rts_argc0 = rts_argc;
484

485
    // process arguments from the -with-rtsopts compile-time flag first
486 487 488 489
    // (arguments from the GHCRTS environment variable and the command
    // line override these).
    {
	if (ghc_rts_opts != NULL) {
490 491 492 493 494
            splitRtsFlags(ghc_rts_opts);
            // opts from ghc_rts_opts are always enabled:
            procRtsOpts(rts_argc0, RtsOptsAll);
            rts_argc0 = rts_argc;
        }
495 496
    }

497
    // process arguments from the GHCRTS environment variable next
498
    // (arguments from the command line override these).
499 500 501 502
    {
	char *ghc_rts = getenv("GHCRTS");

	if (ghc_rts != NULL) {
503
            if (rtsOptsEnabled == RtsOptsNone) {
504
                errorBelch("Warning: Ignoring GHCRTS variable as RTS options are disabled.\n         Link with -rtsopts to enable them.");
505
                // We don't actually exit, just warn
506 507 508 509
            } else {
                splitRtsFlags(ghc_rts);
                procRtsOpts(rts_argc0, rtsOptsEnabled);
                rts_argc0 = rts_argc;
510
            }
511
        }
512
    }
513

514 515 516
    // Split arguments (argv) into PGM (argv) and RTS (rts_argv) parts
    //   argv[0] must be PGM argument -- leave in argv

517 518 519 520 521 522 523 524 525 526 527 528
    for (mode = PGM; arg < total_arg; arg++) {
	// The '--RTS' argument disables all future +RTS ... -RTS processing.
	if (strequal("--RTS", argv[arg])) {
	    arg++;
	    break;
	}
	// The '--' argument is passed through to the program, but
	// disables all further +RTS ... -RTS processing.
	else if (strequal("--", argv[arg])) {
	    break;
	}
	else if (strequal("+RTS", argv[arg])) {
529 530
            mode = RTS;
        }
531 532 533
	else if (strequal("-RTS", argv[arg])) {
	    mode = PGM;
	}
534
        else if (mode == RTS) {
535
            appendRtsArg(copyArg(argv[arg]));
Ian Lynagh's avatar
Ian Lynagh committed
536
        }
537 538
        else {
            argv[(*argc)++] = argv[arg];
539 540
	}
    }
541 542 543
    // process remaining program arguments
    for (; arg < total_arg; arg++) {
	argv[(*argc)++] = argv[arg];
544 545
    }
    argv[*argc] = (char *) 0;
546 547 548

    procRtsOpts(rts_argc0, rtsOptsEnabled);

549 550
    appendRtsArg((char *)0);

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    normaliseRtsOpts();

    setProgArgv(*argc, argv);

    if (RtsFlags.GcFlags.statsFile != NULL) {
        initStatsFile (RtsFlags.GcFlags.statsFile);
    }
    if (RtsFlags.TickyFlags.tickyFile != NULL) {
        initStatsFile (RtsFlags.GcFlags.statsFile);
    }
}

/* -----------------------------------------------------------------------------
 * procRtsOpts: Process rts_argv between rts_argc0 and rts_argc.
 * -------------------------------------------------------------------------- */

567 568 569
static void checkSuid(RtsOptsEnabledEnum enabled)
{
    if (enabled == RtsOptsSafeOnly) {
570
#if defined(HAVE_UNISTD_H) && defined(HAVE_SYS_TYPES_H) && !defined(mingw32_HOST_OS)
571 572 573 574 575 576 577
	/* This doesn't cover linux/posix capabilities like CAP_DAC_OVERRIDE,
	   we'd have to link with -lcap for that. */
        if ((getuid() != geteuid()) || (getgid() != getegid())) {
            errorBelch("RTS options are disabled for setuid binaries. Link with -rtsopts to enable them.");
            stg_exit(EXIT_FAILURE);
        }
#endif
578
    }
579 580 581 582 583 584 585 586 587 588
}

static void checkUnsafe(RtsOptsEnabledEnum enabled)
{
    if (enabled == RtsOptsSafeOnly) {
        errorBelch("Most RTS options are disabled. Link with -rtsopts to enable them.");
        stg_exit(EXIT_FAILURE);
    }
}

589
static void procRtsOpts (int rts_argc0, RtsOptsEnabledEnum rtsOptsEnabled)
590 591 592
{
    rtsBool error = rtsFalse;
    int arg;
593

594 595
    if (!(rts_argc0 < rts_argc)) return;

596
    if (rtsOptsEnabled == RtsOptsNone) {
597 598 599 600 601 602
        errorBelch("RTS options are disabled. Link with -rtsopts to enable them.");
        stg_exit(EXIT_FAILURE);
    }

    checkSuid(rtsOptsEnabled);

603
    // Process RTS (rts_argv) part: mainly to determine statsfile
604
    for (arg = rts_argc0; arg < rts_argc; arg++) {
605 606 607 608 609 610 611 612

        /* We handle RtsOptsSafeOnly mode by declaring each option as
	   either OPTION_SAFE or OPTION_UNSAFE. To make sure we cover
	   every branch we use an option_checked flag which is reset
	   at the start each iteration and checked at the end. */
        rtsBool option_checked = rtsFalse;

#define OPTION_SAFE option_checked = rtsTrue;
613
#define OPTION_UNSAFE checkUnsafe(rtsOptsEnabled); option_checked = rtsTrue;
614

615
        if (rts_argv[arg][0] != '-') {
616
	    fflush(stdout);
617
	    errorBelch("unexpected RTS argument: %s", rts_argv[arg]);
618 619 620
	    error = rtsTrue;

        } else {
Simon Marlow's avatar
Simon Marlow committed
621 622

            switch(rts_argv[arg][1]) {
623

Simon Marlow's avatar
Simon Marlow committed
624 625 626 627 628
	      /* process: general args, then PROFILING-only ones, then
		 CONCURRENT-only, TICKY-only (same order as defined in
		 RtsFlags.lh); within those groups, mostly in
		 case-insensitive alphabetical order.  Final group is
		 x*, which allows for more options.
629 630 631 632 633 634
	      */

#ifdef TICKY_TICKY
# define TICKY_BUILD_ONLY(x) x
#else
# define TICKY_BUILD_ONLY(x) \
635
errorBelch("the flag %s requires the program to be built with -ticky", rts_argv[arg]); \
636 637 638 639 640 641 642
error = rtsTrue;
#endif

#ifdef PROFILING
# define PROFILING_BUILD_ONLY(x)   x
#else
# define PROFILING_BUILD_ONLY(x) \
643
errorBelch("the flag %s requires the program to be built with -prof", rts_argv[arg]); \
644 645 646
error = rtsTrue;
#endif

647 648
#ifdef TRACING
# define TRACING_BUILD_ONLY(x)   x
Simon Marlow's avatar
Simon Marlow committed
649
#else
650
# define TRACING_BUILD_ONLY(x) \
651
errorBelch("the flag %s requires the program to be built with -eventlog or -debug", rts_argv[arg]); \
Simon Marlow's avatar
Simon Marlow committed
652 653 654
error = rtsTrue;
#endif

655 656 657 658
#ifdef THREADED_RTS
# define THREADED_BUILD_ONLY(x)      x
#else
# define THREADED_BUILD_ONLY(x) \
659 660 661 662 663 664 665 666 667
errorBelch("the flag %s requires the program to be built with -threaded", rts_argv[arg]); \
error = rtsTrue;
#endif

#ifdef DEBUG
# define DEBUG_BUILD_ONLY(x) x
#else
# define DEBUG_BUILD_ONLY(x) \
errorBelch("the flag %s requires the program to be built with -debug", rts_argv[arg]); \
668
error = rtsTrue;
669 670 671 672
#endif

	      /* =========== GENERAL ========================== */
	      case '?':
673
		OPTION_SAFE;
674 675 676
		error = rtsTrue;
		break;

677 678 679 680 681 682
              /* This isn't going to allow us to keep related options
                 together as we add more --* flags. We really need a
                 proper options parser. */
	      case '-':
                  if (strequal("install-signal-handlers=yes",
                               &rts_argv[arg][2])) {
683
                      OPTION_UNSAFE;
684 685 686 687
                      RtsFlags.MiscFlags.install_signal_handlers = rtsTrue;
                  }
                  else if (strequal("install-signal-handlers=no",
                               &rts_argv[arg][2])) {
688
                      OPTION_UNSAFE;
689 690
                      RtsFlags.MiscFlags.install_signal_handlers = rtsFalse;
                  }
Ian Lynagh's avatar
Ian Lynagh committed
691 692
                  else if (strequal("machine-readable",
                               &rts_argv[arg][2])) {
693
                      OPTION_UNSAFE;
Ian Lynagh's avatar
Ian Lynagh committed
694 695
                      RtsFlags.MiscFlags.machineReadable = rtsTrue;
                  }
696 697
                  else if (strequal("info",
                               &rts_argv[arg][2])) {
698
                      OPTION_SAFE;
699
                      printRtsInfo();
700
                      stg_exit(0);
701
                  }
702
                  else {
703
		      OPTION_SAFE;
704 705 706 707
		      errorBelch("unknown RTS option: %s",rts_argv[arg]);
		      error = rtsTrue;
                  }
		  break;
708
	      case 'A':
709
        	  OPTION_UNSAFE;
710 711 712 713
                  RtsFlags.GcFlags.minAllocAreaSize
                      = decodeSize(rts_argv[arg], 2, BLOCK_SIZE, HS_INT_MAX)
                           / BLOCK_SIZE;
                  break;
714

715 716
#ifdef USE_PAPI
	      case 'a':
717
        	OPTION_UNSAFE;
718 719 720 721 722 723 724 725 726 727 728 729 730
		switch(rts_argv[arg][2]) {
		case '1':
		  RtsFlags.PapiFlags.eventType = PAPI_FLAG_CACHE_L1;
		  break;
		case '2':
		  RtsFlags.PapiFlags.eventType = PAPI_FLAG_CACHE_L2;
		  break;
		case 'b':
		  RtsFlags.PapiFlags.eventType = PAPI_FLAG_BRANCH;
		  break;
		case 's':
		  RtsFlags.PapiFlags.eventType = PAPI_FLAG_STALLS;
		  break;
731 732 733
		case 'e':
		  RtsFlags.PapiFlags.eventType = PAPI_FLAG_CB_EVENTS;
		  break;
734
                case '+':
735
                case '#':
736 737 738 739
                  if (RtsFlags.PapiFlags.numUserEvents >= MAX_PAPI_USER_EVENTS) {
                      errorBelch("maximum number of PAPI events reached");
                      stg_exit(EXIT_FAILURE);
                  }
740 741 742 743 744
                  nat eventNum  = RtsFlags.PapiFlags.numUserEvents++;
                  char kind     = rts_argv[arg][2];
                  nat eventKind = kind == '+' ? PAPI_PRESET_EVENT_KIND : PAPI_NATIVE_EVENT_KIND;

                  RtsFlags.PapiFlags.userEvents[eventNum] = rts_argv[arg] + 3;
745
                  RtsFlags.PapiFlags.eventType = PAPI_USER_EVENTS;
746
                  RtsFlags.PapiFlags.userEventsKind[eventNum] = eventKind;
747
                  break;
748 749 750 751 752 753
		default:
		  bad_option( rts_argv[arg] );
		}
		break;
#endif

754
	      case 'B':
755
        	OPTION_UNSAFE;
756 757 758
		RtsFlags.GcFlags.ringBell = rtsTrue;
		break;

759
	      case 'c':
760
        	  OPTION_UNSAFE;
761 762 763 764
		  if (rts_argv[arg][2] != '\0') {
		      RtsFlags.GcFlags.compactThreshold =
			  atof(rts_argv[arg]+2);
		  } else {
765
		      RtsFlags.GcFlags.compact = rtsTrue;
766 767
		  }
		  break;
768

769
              case 'w':
770
        	OPTION_UNSAFE;
771 772 773
		RtsFlags.GcFlags.sweep = rtsTrue;
		break;

774
	      case 'F':
775
        	OPTION_UNSAFE;
776 777 778 779 780 781
	        RtsFlags.GcFlags.oldGenFactor = atof(rts_argv[arg]+2);
	      
		if (RtsFlags.GcFlags.oldGenFactor < 0)
		  bad_option( rts_argv[arg] );
		break;
	      
782
	      case 'D':
783
              OPTION_SAFE;
784
              DEBUG_BUILD_ONLY(
785 786 787 788 789 790 791 792
	      { 
		  char *c;

		  for (c  = rts_argv[arg] + 2; *c != '\0'; c++) {
		      switch (*c) {
		      case 's':
			  RtsFlags.DebugFlags.scheduler = rtsTrue;
			  break;
793 794
		      case 'i':
			  RtsFlags.DebugFlags.interpreter = rtsTrue;
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
			  break;
		      case 'w':
			  RtsFlags.DebugFlags.weak = rtsTrue;
			  break;
		      case 'G':
			  RtsFlags.DebugFlags.gccafs = rtsTrue;
			  break;
		      case 'g':
			  RtsFlags.DebugFlags.gc = rtsTrue;
			  break;
		      case 'b':
			  RtsFlags.DebugFlags.block_alloc = rtsTrue;
			  break;
		      case 'S':
			  RtsFlags.DebugFlags.sanity = rtsTrue;
			  break;
		      case 't':
			  RtsFlags.DebugFlags.stable = rtsTrue;
			  break;
		      case 'p':
			  RtsFlags.DebugFlags.prof = rtsTrue;
			  break;
		      case 'l':
			  RtsFlags.DebugFlags.linker = rtsTrue;
			  break;
820 821 822
		      case 'a':
			  RtsFlags.DebugFlags.apply = rtsTrue;
			  break;
823 824 825
		      case 'm':
			  RtsFlags.DebugFlags.stm = rtsTrue;
			  break;
826 827 828
		      case 'z':
			  RtsFlags.DebugFlags.squeeze = rtsTrue;
			  break;
829 830 831
		      case 'c':
			  RtsFlags.DebugFlags.hpc = rtsTrue;
			  break;
832 833 834
		      case 'r':
			  RtsFlags.DebugFlags.sparks = rtsTrue;
			  break;
835 836 837 838
		      default:
			  bad_option( rts_argv[arg] );
		      }
		  }
839 840
                  // -Dx also turns on -v.  Use -l to direct trace
                  // events to the .eventlog file instead.
841
                  RtsFlags.TraceFlags.tracing = TRACE_STDERR;
842 843
	      })
              break;
844 845

	      case 'K':
846
        	  OPTION_UNSAFE;
847
                  RtsFlags.GcFlags.maxStkSize =
848
                      decodeSize(rts_argv[arg], 2, sizeof(W_), HS_WORD_MAX) / sizeof(W_);
849
                  break;
850 851

	      case 'k':
852
        	OPTION_UNSAFE;
853 854 855 856 857 858 859 860 861 862 863 864 865 866
		switch(rts_argv[arg][2]) {
                case 'c':
                  RtsFlags.GcFlags.stkChunkSize =
                      decodeSize(rts_argv[arg], 3, sizeof(W_), HS_WORD_MAX) / sizeof(W_);
                  break;
                case 'b':
                  RtsFlags.GcFlags.stkChunkBufferSize =
                      decodeSize(rts_argv[arg], 3, sizeof(W_), HS_WORD_MAX) / sizeof(W_);
                  break;
                case 'i':
                  RtsFlags.GcFlags.initialStkSize =
                      decodeSize(rts_argv[arg], 3, sizeof(W_), HS_WORD_MAX) / sizeof(W_);
                  break;
                default:
867
                  RtsFlags.GcFlags.initialStkSize =
868
                      decodeSize(rts_argv[arg], 2, sizeof(W_), HS_WORD_MAX) / sizeof(W_);
869
                  break;
870 871
                }
                break;
872

873
              case 'M':
874
        	  OPTION_UNSAFE;
875 876 877 878
                  RtsFlags.GcFlags.maxHeapSize =
                      decodeSize(rts_argv[arg], 2, BLOCK_SIZE, HS_WORD_MAX) / BLOCK_SIZE;
                  /* user give size in *bytes* but "maxHeapSize" is in *blocks* */
                  break;
879 880

	      case 'm':
881
        	  OPTION_UNSAFE;
882
                  RtsFlags.GcFlags.pcFreeHeap = atof(rts_argv[arg]+2);
883

884 885 886 887
                  if (RtsFlags.GcFlags.pcFreeHeap < 0 ||
                      RtsFlags.GcFlags.pcFreeHeap > 100)
                      bad_option( rts_argv[arg] );
                  break;
888

889
	      case 'G':
890
        	  OPTION_UNSAFE;
891 892 893
                  RtsFlags.GcFlags.generations =
                      decodeSize(rts_argv[arg], 2, 1, HS_INT_MAX);
                  break;
894

895
	      case 'H':
896
        	  OPTION_UNSAFE;
897 898 899 900 901 902 903
                  if (rts_argv[arg][2] == '\0') {
                      RtsFlags.GcFlags.heapSizeSuggestionAuto = rtsTrue;
                  } else {
                      RtsFlags.GcFlags.heapSizeSuggestion =
                          (nat)(decodeSize(rts_argv[arg], 2, BLOCK_SIZE, HS_WORD_MAX) / BLOCK_SIZE);
                  }
                  break;
904

905 906
#ifdef RTS_GTK_FRONTPANEL
	      case 'f':
907
        	  OPTION_UNSAFE;
908 909 910 911
		  RtsFlags.GcFlags.frontpanel = rtsTrue;
		  break;
#endif

912
    	      case 'I':	/* idle GC delay */
913
        	OPTION_UNSAFE;
914 915 916
		if (rts_argv[arg][2] == '\0') {
		  /* use default */
		} else {
Simon Marlow's avatar
Simon Marlow committed
917 918
                    RtsFlags.GcFlags.idleGCDelayTime =
                        fsecondsToTime(atof(rts_argv[arg]+2));
919 920 921
		}
		break;

922
              case 'T':
923
        	  OPTION_SAFE;
924 925 926
                  RtsFlags.GcFlags.giveStats = COLLECT_GC_STATS;
                  break; /* Don't initialize statistics file. */

927
	      case 'S':
928
		  OPTION_SAFE; /* but see below */
929 930
		  RtsFlags.GcFlags.giveStats = VERBOSE_GC_STATS;
		  goto stats;
931

932
	      case 's':