RtsStartup.c 11.4 KB
Newer Older
1
/* -----------------------------------------------------------------------------
2
 *
3
 * (c) The GHC Team, 1998-2002
4 5 6 7 8
 *
 * Main function for a standalone Haskell program.
 *
 * ---------------------------------------------------------------------------*/

mrchebas@gmail.com's avatar
mrchebas@gmail.com committed
9
// PAPI uses caddr_t, which is not POSIX
Simon Marlow's avatar
Simon Marlow committed
10 11 12
#ifndef USE_PAPI
#include "PosixSource.h"
#endif
mrchebas@gmail.com's avatar
mrchebas@gmail.com committed
13

14 15
#include "Rts.h"
#include "RtsAPI.h"
Simon Marlow's avatar
Simon Marlow committed
16 17 18
#include "HsFFI.h"

#include "sm/Storage.h"
19
#include "RtsFlags.h"
20
#include "RtsUtils.h"
21
#include "Prelude.h"
22 23
#include "Schedule.h"   /* initScheduler */
#include "Stats.h"      /* initStats */
24
#include "STM.h"        /* initSTM */
25
#include "RtsSignals.h"
26
#include "Weak.h"
27
#include "Ticky.h"
28
#include "StgRun.h"
29
#include "Prelude.h"		/* fixupRTStoPreludeRefs */
30
#include "ThreadLabels.h"
Simon Marlow's avatar
Simon Marlow committed
31
#include "sm/BlockAlloc.h"
Simon Marlow's avatar
Simon Marlow committed
32
#include "Trace.h"
33
#include "Stable.h"
Simon Marlow's avatar
Simon Marlow committed
34
#include "Hash.h"
Simon Marlow's avatar
Simon Marlow committed
35 36 37
#include "Profiling.h"
#include "Timer.h"
#include "Globals.h"
pcapriotti's avatar
pcapriotti committed
38
#include "FileLock.h"
39
void exitLinker( void );	// there is no Linker.h file to include
40

41 42 43 44
#if defined(RTS_GTK_FRONTPANEL)
#include "FrontPanel.h"
#endif

45
#if defined(PROFILING)
46
# include "ProfHeap.h"
47
# include "RetainerProfile.h"
48 49
#endif

50
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
sof's avatar
sof committed
51 52 53
#include "win32/AsyncIO.h"
#endif

Simon Marlow's avatar
Simon Marlow committed
54 55
#if !defined(mingw32_HOST_OS)
#include "posix/TTY.h"
56
#endif
Simon Marlow's avatar
Simon Marlow committed
57

Simon Marlow's avatar
Simon Marlow committed
58 59 60
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
61 62 63
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
64

mrchebas@gmail.com's avatar
mrchebas@gmail.com committed
65 66 67 68
#if USE_PAPI
#include "Papi.h"
#endif

69 70
// Count of how many outstanding hs_init()s there have been.
static int hs_init_count = 0;
71

72 73
static void flushStdHandles(void);

74 75 76 77 78
const RtsConfig defaultRtsConfig  = {
    .rts_opts_enabled = RtsOptsSafeOnly,
    .rts_opts = NULL
};

79
/* -----------------------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
80 81
   Initialise floating point unit on x86 (currently disabled; See Note
   [x86 Floating point precision] in compiler/nativeGen/X86/Instr.hs)
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
   -------------------------------------------------------------------------- */

#define X86_INIT_FPU 0

#if X86_INIT_FPU
static void
x86_init_fpu ( void )
{
  __volatile unsigned short int fpu_cw;

  // Grab the control word
  __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));

#if 0
  printf("fpu_cw: %x\n", fpu_cw);
#endif

  // Set bits 8-9 to 10 (64-bit precision).
  fpu_cw = (fpu_cw & 0xfcff) | 0x0200;

  // Store the new control word back
  __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
}
105 106
#endif

107 108 109
/* -----------------------------------------------------------------------------
   Starting up the RTS
   -------------------------------------------------------------------------- */
110

sof's avatar
sof committed
111
void
112
hs_init(int *argc, char **argv[])
113 114 115 116 117 118
{
    hs_init_ghc(argc, argv, defaultRtsConfig);
}

void
hs_init_ghc(int *argc, char **argv[], RtsConfig rts_config)
119
{
120 121 122 123
    hs_init_count++;
    if (hs_init_count > 1) {
	// second and subsequent inits are ignored
	return;
sof's avatar
sof committed
124
    }
sof's avatar
sof committed
125

126 127
    setlocale(LC_CTYPE,"");

128 129
    /* Initialise the stats department, phase 0 */
    initStats0();
130

131 132 133
    /* Initialize system timer before starting to collect stats */
    initializeTimer();

134
    /* Next we do is grab the start time...just in case we're
135 136
     * collecting timing statistics.
     */
137
    stat_startInit();
138 139

    /* Set the RTS flags to default values. */
mrchebas@gmail.com's avatar
mrchebas@gmail.com committed
140

141 142 143 144 145 146
    initRtsFlagsDefaults();

    /* Call the user hook to reset defaults, if present */
    defaultsHook();

    /* Parse the flags, separating the RTS flags from the programs args */
147 148 149 150 151 152 153 154
    if (argc == NULL || argv == NULL) {
        // Use a default for argc & argv if either is not supplied
        int my_argc = 1;
        char *my_argv[] = { "<unknown>", NULL };
        setFullProgArgv(my_argc,my_argv);
        setupRtsFlags(&my_argc, my_argv,
                      rts_config.rts_opts_enabled, rts_config.rts_opts);
    } else {
Gabor Greif's avatar
Gabor Greif committed
155
        setFullProgArgv(*argc,*argv);
156 157
        setupRtsFlags(argc, *argv,
                      rts_config.rts_opts_enabled, rts_config.rts_opts);
158
    }
159

160 161 162
    /* Initialise the stats department, phase 1 */
    initStats1();

163 164 165 166
#ifdef USE_PAPI
    papi_init();
#endif

Simon Marlow's avatar
Simon Marlow committed
167
    /* initTracing must be after setupRtsFlags() */
168
#ifdef TRACING
Simon Marlow's avatar
Simon Marlow committed
169
    initTracing();
Simon Marlow's avatar
Simon Marlow committed
170
#endif
171
    /* Trace the startup event
172
     */
173
    traceEventStartup();
Simon Marlow's avatar
Simon Marlow committed
174

175 176 177 178 179
    /* initialise scheduler data structures (needs to be done before
     * initStorage()).
     */
    initScheduler();

180
    /* Trace some basic information about the process */
181
    traceWallClockTime();
182 183
    traceOSProcessInfo();

184 185 186 187 188 189
    /* initialize the storage manager */
    initStorage();

    /* initialise the stable pointer table */
    initStablePtrTable();

190 191 192
    /* Add some GC roots for things in the base package that the RTS
     * knows about.  We don't know whether these turn out to be CAFs
     * or refer to CAFs, but we have to assume that they might.
193
     */
194 195
    getStablePtr((StgPtr)runIO_closure);
    getStablePtr((StgPtr)runNonIO_closure);
196
    getStablePtr((StgPtr)flushStdHandles_closure);
197 198 199

    getStablePtr((StgPtr)runFinalizerBatch_closure);

200 201 202
    getStablePtr((StgPtr)stackOverflow_closure);
    getStablePtr((StgPtr)heapOverflow_closure);
    getStablePtr((StgPtr)unpackCString_closure);
Simon Marlow's avatar
Simon Marlow committed
203
    getStablePtr((StgPtr)blockedIndefinitelyOnMVar_closure);
204
    getStablePtr((StgPtr)nonTermination_closure);
Simon Marlow's avatar
Simon Marlow committed
205
    getStablePtr((StgPtr)blockedIndefinitelyOnSTM_closure);
206 207 208 209
    getStablePtr((StgPtr)nestedAtomically_closure);

    getStablePtr((StgPtr)runSparks_closure);
    getStablePtr((StgPtr)ensureIOManagerIsRunning_closure);
210
#ifndef mingw32_HOST_OS
211
    getStablePtr((StgPtr)runHandlers_closure);
212
#endif
213

ei@vuokko.info's avatar
ei@vuokko.info committed
214
    /* initialise the shared Typeable store */
215
    initGlobalStore();
ei@vuokko.info's avatar
ei@vuokko.info committed
216

217 218 219
    /* initialise file locking, if necessary */
    initFileLocking();

sof's avatar
sof committed
220
#if defined(DEBUG)
221 222
    /* initialise thread label table (tso->char*) */
    initThreadLabelTable();
sof's avatar
sof committed
223
#endif
224

225 226
    initProfiling1();

sof's avatar
sof committed
227
    /* start the virtual timer 'subsystem'. */
228
    initTimer();
229
    startTimer();
230

sof's avatar
sof committed
231
#if defined(RTS_USER_SIGNALS)
232 233 234 235 236 237
    if (RtsFlags.MiscFlags.install_signal_handlers) {
        /* Initialise the user signal handler set */
        initUserSignals();
        /* Set up handler to run on SIGINT, etc. */
        initDefaultHandlers();
    }
sof's avatar
sof committed
238
#endif
sof's avatar
sof committed
239
 
240
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
sof's avatar
sof committed
241 242 243
    startupAsyncIO();
#endif

244 245 246 247 248 249
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	initFrontPanel();
    }
#endif

250 251
#if X86_INIT_FPU
    x86_init_fpu();
252 253
#endif

254 255 256 257 258 259 260 261 262 263 264
    startupHpc();

    // This must be done after module initialisation.
    // ToDo: make this work in the presence of multiple hs_add_root()s.
    initProfiling2();

    // ditto.
#if defined(THREADED_RTS)
    ioManagerStart();
#endif

265
    /* Record initialization times */
266
    stat_endInit();
267 268
}

269 270
// Compatibility interface
void
271
startupHaskell(int argc, char *argv[], void (*init_root)(void) STG_UNUSED)
272 273 274 275 276
{
    hs_init(&argc, &argv);
}


277
/* -----------------------------------------------------------------------------
278
   hs_add_root: backwards compatibility.  (see #3252)
279 280
   -------------------------------------------------------------------------- */

281
void
282
hs_add_root(void (*init_root)(void) STG_UNUSED)
283
{
284
    /* nothing */
285
}
286

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
/* ----------------------------------------------------------------------------
 * Shutting down the RTS
 *
 * The wait_foreign parameter means:
 *       True  ==> wait for any threads doing foreign calls now.
 *       False ==> threads doing foreign calls may return in the
 *                 future, but will immediately block on a mutex.
 *                 (capability->lock).
 * 
 * If this RTS is a DLL that we're about to unload, then you want
 * safe=True, otherwise the thread might return to code that has been
 * unloaded.  If this is a standalone program that is about to exit,
 * then you can get away with safe=False, which is better because we
 * won't hang on exit if there is a blocked foreign call outstanding.
 *
 ------------------------------------------------------------------------- */
sof's avatar
sof committed
303

304 305
static void
hs_exit_(rtsBool wait_foreign)
306
{
307
    if (hs_init_count <= 0) {
308 309
	errorBelch("warning: too many hs_exit()s");
	return;
310 311 312 313 314 315
    }
    hs_init_count--;
    if (hs_init_count > 0) {
	// ignore until it's the last one
	return;
    }
sof's avatar
sof committed
316

317 318 319
    /* start timing the shutdown */
    stat_startExit();
    
Simon Marlow's avatar
Simon Marlow committed
320 321
    OnExitHook();

322 323
    flushStdHandles();

324 325 326 327 328
    // sanity check
#if defined(DEBUG)
    checkFPUStack();
#endif

329
#if defined(THREADED_RTS)
330 331 332
    ioManagerDie();
#endif

333
    /* stop all running tasks */
334
    exitScheduler(wait_foreign);
335 336 337

    /* run C finalizers for all active weak pointers */
    runAllCFinalizers(weak_ptr_list);
338
    
339 340 341 342 343 344
#if defined(RTS_USER_SIGNALS)
    if (RtsFlags.MiscFlags.install_signal_handlers) {
        freeSignalHandlers();
    }
#endif

345
    /* stop the ticker */
sof's avatar
sof committed
346
    stopTimer();
347
    exitTimer(wait_foreign);
348

Simon Marlow's avatar
Simon Marlow committed
349 350 351
    // set the terminal settings back to what they were
#if !defined(mingw32_HOST_OS)    
    resetTerminalSettings();
352 353
#endif

Simon Marlow's avatar
Simon Marlow committed
354 355 356
    // uninstall signal handlers
    resetDefaultHandlers();

357 358 359
    /* stop timing the shutdown, we're about to print stats */
    stat_endExit();
    
andy@galois.com's avatar
andy@galois.com committed
360 361 362
    /* shutdown the hpc support (if needed) */
    exitHpc();

Simon Marlow's avatar
Simon Marlow committed
363 364
    // clean up things from the storage manager's point of view.
    // also outputs the stats (+RTS -s) info.
365 366
    exitStorage();
    
367 368 369
    /* free the tasks */
    freeScheduler();

ei@vuokko.info's avatar
ei@vuokko.info committed
370
    /* free shared Typeable store */
371
    exitGlobalStore();
ei@vuokko.info's avatar
ei@vuokko.info committed
372

373 374 375
    /* free linker data */
    exitLinker();

376 377 378
    /* free file locking tables, if necessary */
    freeFileLocking();

Ian Lynagh's avatar
Ian Lynagh committed
379
    /* free the stable pointer table */
380 381
    exitStablePtrTable();

Ian Lynagh's avatar
Ian Lynagh committed
382 383 384 385 386
#if defined(DEBUG)
    /* free the thread label table */
    freeThreadLabelTable();
#endif

387 388 389 390 391 392
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	stopFrontPanel();
    }
#endif

393
#if defined(PROFILING) 
394
    reportCCSProfiling();
395 396
#endif

397
    endProfiling();
398
    freeProfiling();
399

400
#ifdef PROFILING
401 402 403
    // Originally, this was in report_ccs_profiling().  Now, retainer
    // profiling might tack some extra stuff on to the end of this file
    // during endProfiling().
404
    if (prof_file != NULL) fclose(prof_file);
405
#endif
Simon Marlow's avatar
Simon Marlow committed
406

407 408 409
#ifdef TRACING
    endTracing();
    freeTracing();
Simon Marlow's avatar
Simon Marlow committed
410 411
#endif

412
#if defined(TICKY_TICKY)
413 414
    if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
#endif
sof's avatar
sof committed
415

416
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
Simon Marlow's avatar
Simon Marlow committed
417
    shutdownAsyncIO(wait_foreign);
sof's avatar
sof committed
418
#endif
Simon Marlow's avatar
Simon Marlow committed
419

420 421 422
    /* free hash table storage */
    exitHashTable();

423 424 425 426 427
    // Finally, free all our storage.  However, we only free the heap
    // memory if we have waited for foreign calls to complete;
    // otherwise a foreign call in progress may still be referencing
    // heap memory (e.g. by being passed a ByteArray#).
    freeStorage(wait_foreign);
428

429 430
    // Free the various argvs
    freeRtsArgs();
431 432
}

433 434 435 436 437 438 439
// Flush stdout and stderr.  We do this during shutdown so that it
// happens even when the RTS is being used as a library, without a
// main (#5594)
static void flushStdHandles(void)
{
    Capability *cap;
    cap = rts_lock();
440
    rts_evalIO(&cap, flushStdHandles_closure, NULL);
441 442 443
    rts_unlock(cap);
}

444 445 446 447 448 449 450 451
// The real hs_exit():
void
hs_exit(void)
{
    hs_exit_(rtsTrue);
    // be safe; this might be a DLL
}

452 453 454 455 456 457 458 459 460 461
// Compatibility interfaces
void
shutdownHaskell(void)
{
    hs_exit();
}

void
shutdownHaskellAndExit(int n)
{
462 463 464 465
    // even if hs_init_count > 1, we still want to shut down the RTS
    // and exit immediately (see #5402)
    hs_init_count = 1;

Simon Marlow's avatar
Simon Marlow committed
466 467 468
    // we're about to exit(), no need to wait for foreign calls to return.
    hs_exit_(rtsFalse);

469
    stg_exit(n);
470
}
471

Simon Marlow's avatar
Simon Marlow committed
472 473 474 475 476 477 478 479 480
#ifndef mingw32_HOST_OS
void
shutdownHaskellAndSignal(int sig)
{
    hs_exit_(rtsFalse);
    kill(getpid(),sig);
}
#endif

481
/* 
482
 * called from STG-land to exit the program
483 484
 */

485 486
void (*exitFn)(int) = 0;

487
void  
488
stg_exit(int n)
489
{ 
490 491
  if (exitFn)
    (*exitFn)(n);
492
  exit(n);
493
}