RtsStartup.c 12.7 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 10 11
// PAPI uses caddr_t, which is not POSIX
// #include "PosixSource.h"

12 13 14 15
#include "Rts.h"
#include "RtsAPI.h"
#include "RtsUtils.h"
#include "RtsFlags.h"  
16
#include "OSThreads.h"
17 18
#include "Schedule.h"   /* initScheduler */
#include "Stats.h"      /* initStats */
19
#include "STM.h"        /* initSTM */
20
#include "Signals.h"
21
#include "RtsSignals.h"
22
#include "ThrIOManager.h"
sof's avatar
sof committed
23
#include "Timer.h"      /* startTimer, stopTimer */
24
#include "Weak.h"
25
#include "Ticky.h"
26
#include "StgRun.h"
27
#include "Prelude.h"		/* fixupRTStoPreludeRefs */
28 29
#include "HsFFI.h"
#include "Linker.h"
30
#include "ThreadLabels.h"
31
#include "BlockAlloc.h"
Simon Marlow's avatar
Simon Marlow committed
32
#include "Trace.h"
33
#include "RtsGlobals.h"
34
#include "Stable.h"
35
#include "Hpc.h"
36
#include "FileLock.h"
Simon Marlow's avatar
Simon Marlow committed
37
#include "EventLog.h"
Simon Marlow's avatar
Simon Marlow committed
38
#include "Hash.h"
39

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

44
# include "Profiling.h"
45 46

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

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

55 56
#include <stdlib.h>

57 58 59 60 61 62
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
Simon Marlow's avatar
Simon Marlow committed
63 64 65
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
66

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

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

74 75 76
// Here we save the terminal settings on the standard file
// descriptors, if we need to change them (eg. to support NoBuffering
// input).
77 78 79 80 81
static void *saved_termios[3] = {NULL,NULL,NULL};

void*
__hscore_get_saved_termios(int fd)
{
82
  return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
83 84 85 86 87 88
    saved_termios[fd] : NULL;
}

void
__hscore_set_saved_termios(int fd, void* ts)
{
89
  if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
90 91 92
    saved_termios[fd] = ts;
  }
}
93

94 95
/* -----------------------------------------------------------------------------
   Initialise floating point unit on x86 (currently disabled. why?)
96
   (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
   -------------------------------------------------------------------------- */

#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));
}
120 121
#endif

122 123 124
/* -----------------------------------------------------------------------------
   Starting up the RTS
   -------------------------------------------------------------------------- */
125

sof's avatar
sof committed
126
void
127
hs_init(int *argc, char **argv[])
128
{
129 130 131 132
    hs_init_count++;
    if (hs_init_count > 1) {
	// second and subsequent inits are ignored
	return;
sof's avatar
sof committed
133
    }
sof's avatar
sof committed
134

135 136
    /* Initialise the stats department, phase 0 */
    initStats0();
137 138

    /* Next we do is grab the start time...just in case we're
139 140
     * collecting timing statistics.
     */
141
    stat_startInit();
142

143 144 145 146 147 148
#if defined(DEBUG)
    /* Start off by initialising the allocator debugging so we can
     * use it anywhere */
    initAllocator();
#endif

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

151 152 153 154 155 156
    initRtsFlagsDefaults();

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

    /* Parse the flags, separating the RTS flags from the programs args */
157
    if (argc != NULL && argv != NULL) {
158
	setFullProgArgv(*argc,*argv);
159
	setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
160
	setProgArgv(*argc,*argv);
161
    }
162

163 164 165
    /* Initialise the stats department, phase 1 */
    initStats1();

166 167 168 169
#ifdef USE_PAPI
    papi_init();
#endif

Simon Marlow's avatar
Simon Marlow committed
170
    /* initTracing must be after setupRtsFlags() */
Simon Marlow's avatar
Simon Marlow committed
171
#ifdef DEBUG
Simon Marlow's avatar
Simon Marlow committed
172
    initTracing();
Simon Marlow's avatar
Simon Marlow committed
173
#endif
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 181 182 183 184 185
    /* initialize the storage manager */
    initStorage();

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

186 187 188
    /* 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.
189 190 191
     */
    getStablePtr((StgPtr)base_GHCziTopHandler_runIO_closure);
    getStablePtr((StgPtr)base_GHCziTopHandler_runNonIO_closure);
192 193 194 195 196 197 198
    getStablePtr((StgPtr)stackOverflow_closure);
    getStablePtr((StgPtr)heapOverflow_closure);
    getStablePtr((StgPtr)runFinalizerBatch_closure);
    getStablePtr((StgPtr)unpackCString_closure);
    getStablePtr((StgPtr)blockedOnDeadMVar_closure);
    getStablePtr((StgPtr)nonTermination_closure);
    getStablePtr((StgPtr)blockedIndefinitely_closure);
199

ei@vuokko.info's avatar
ei@vuokko.info committed
200
    /* initialise the shared Typeable store */
201
    initGlobalStore();
ei@vuokko.info's avatar
ei@vuokko.info committed
202

203 204 205 206 207
    /* initialise file locking, if necessary */
#if !defined(mingw32_HOST_OS)    
    initFileLocking();
#endif

sof's avatar
sof committed
208
#if defined(DEBUG)
209 210
    /* initialise thread label table (tso->char*) */
    initThreadLabelTable();
sof's avatar
sof committed
211
#endif
212

213 214
    initProfiling1();

Simon Marlow's avatar
Simon Marlow committed
215 216 217 218 219 220
#ifdef EVENTLOG
    if (RtsFlags.EventLogFlags.doEventLogging) {
        initEventLogging();
    }
#endif

sof's avatar
sof committed
221
    /* start the virtual timer 'subsystem'. */
222
    initTimer();
223
    startTimer();
224

sof's avatar
sof committed
225
#if defined(RTS_USER_SIGNALS)
226 227 228 229 230 231
    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
232
#endif
sof's avatar
sof committed
233
 
234
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
sof's avatar
sof committed
235 236 237
    startupAsyncIO();
#endif

238 239 240 241 242 243
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	initFrontPanel();
    }
#endif

244 245
#if X86_INIT_FPU
    x86_init_fpu();
246 247
#endif

248
    /* Record initialization times */
249
    stat_endInit();
250 251
}

252 253 254 255 256
// Compatibility interface
void
startupHaskell(int argc, char *argv[], void (*init_root)(void))
{
    hs_init(&argc, &argv);
257 258
    if(init_root)
        hs_add_root(init_root);
259 260 261
}


262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
/* -----------------------------------------------------------------------------
   Per-module initialisation

   This process traverses all the compiled modules in the program
   starting with "Main", and performing per-module initialisation for
   each one.

   So far, two things happen at initialisation time:

      - we register stable names for each foreign-exported function
        in that module.  This prevents foreign-exported entities, and
	things they depend on, from being garbage collected.

      - we supply a unique integer to each statically declared cost
        centre and cost centre stack in the program.

ken's avatar
ken committed
278 279
   The code generator inserts a small function "__stginit_<module>" in each
   module and calls the registration functions in each of the modules it
280
   imports.
281 282 283 284 285 286 287 288

   The init* functions are compiled in the same way as STG code,
   i.e. without normal C call/return conventions.  Hence we must use
   StgRun to call this stuff.
   -------------------------------------------------------------------------- */

/* The init functions use an explicit stack... 
 */
289
#define INIT_STACK_BLOCKS  4
290
static F_ *init_stack = NULL;
291

292 293
void
hs_add_root(void (*init_root)(void))
294
{
295
    bdescr *bd;
296
    nat init_sp;
297 298 299
    Capability *cap;

    cap = rts_lock();
300

301 302 303 304
    if (hs_init_count <= 0) {
	barf("hs_add_root() must be called after hs_init()");
    }

305 306 307
    /* The initialisation stack grows downward, with sp pointing 
       to the last occupied word */
    init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
308
    bd = allocGroup_lock(INIT_STACK_BLOCKS);
309
    init_stack = (F_ *)bd->start;
310
    init_stack[--init_sp] = (F_)stg_init_finish;
311
    if (init_root != NULL) {
312
	init_stack[--init_sp] = (F_)init_root;
313 314
    }
    
315 316
    cap->r.rSp = (P_)(init_stack + init_sp);
    StgRun((StgFunPtr)stg_init, &cap->r);
317

318
    freeGroup_lock(bd);
319

andy@galois.com's avatar
andy@galois.com committed
320 321
    startupHpc();

322 323 324
    // This must be done after module initialisation.
    // ToDo: make this work in the presence of multiple hs_add_root()s.
    initProfiling2();
Simon Marlow's avatar
Simon Marlow committed
325

326 327
    rts_unlock(cap);

Simon Marlow's avatar
Simon Marlow committed
328 329 330 331
    // ditto.
#if defined(THREADED_RTS)
    ioManagerStart();
#endif
332
}
333

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
/* ----------------------------------------------------------------------------
 * 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
350

351 352
static void
hs_exit_(rtsBool wait_foreign)
353
{
354
    if (hs_init_count <= 0) {
355 356
	errorBelch("warning: too many hs_exit()s");
	return;
357 358 359 360 361 362
    }
    hs_init_count--;
    if (hs_init_count > 0) {
	// ignore until it's the last one
	return;
    }
sof's avatar
sof committed
363

364 365 366
    /* start timing the shutdown */
    stat_startExit();
    
Simon Marlow's avatar
Simon Marlow committed
367 368
    OnExitHook();

369
#if defined(THREADED_RTS)
370 371 372
    ioManagerDie();
#endif

373
    /* stop all running tasks */
374
    exitScheduler(wait_foreign);
375 376 377

    /* run C finalizers for all active weak pointers */
    runAllCFinalizers(weak_ptr_list);
378
    
379 380 381 382 383 384
#if defined(RTS_USER_SIGNALS)
    if (RtsFlags.MiscFlags.install_signal_handlers) {
        freeSignalHandlers();
    }
#endif

385
    /* stop the ticker */
sof's avatar
sof committed
386
    stopTimer();
387
    exitTimer();
388

389 390 391 392
    /* reset the standard file descriptors to blocking mode */
    resetNonBlockingFd(0);
    resetNonBlockingFd(1);
    resetNonBlockingFd(2);
393

394 395 396 397 398 399 400 401 402 403 404 405
#if HAVE_TERMIOS_H
    // Reset the terminal settings on the standard file descriptors,
    // if we changed them.  See System.Posix.Internals.tcSetAttr for
    // more details, including the reason we termporarily disable
    // SIGTTOU here.
    { 
	int fd;
	sigset_t sigset, old_sigset;
	sigemptyset(&sigset);
	sigaddset(&sigset, SIGTTOU);
	sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
	for (fd = 0; fd <= 2; fd++) {
406 407 408
	    struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
	    if (ts != NULL) {
		tcsetattr(fd,TCSANOW,ts);
409 410 411 412 413 414
	    }
	}
	sigprocmask(SIG_SETMASK, &old_sigset, NULL);
    }
#endif

Simon Marlow's avatar
Simon Marlow committed
415 416 417
    // uninstall signal handlers
    resetDefaultHandlers();

418 419 420
    /* stop timing the shutdown, we're about to print stats */
    stat_endExit();
    
andy@galois.com's avatar
andy@galois.com committed
421 422 423
    /* shutdown the hpc support (if needed) */
    exitHpc();

Simon Marlow's avatar
Simon Marlow committed
424 425
    // clean up things from the storage manager's point of view.
    // also outputs the stats (+RTS -s) info.
426 427
    exitStorage();
    
428 429 430
    /* free the tasks */
    freeScheduler();

ei@vuokko.info's avatar
ei@vuokko.info committed
431
    /* free shared Typeable store */
432
    exitGlobalStore();
ei@vuokko.info's avatar
ei@vuokko.info committed
433

434 435 436 437 438
    /* free file locking tables, if necessary */
#if !defined(mingw32_HOST_OS)    
    freeFileLocking();
#endif

Ian Lynagh's avatar
Ian Lynagh committed
439
    /* free the stable pointer table */
440 441
    exitStablePtrTable();

Ian Lynagh's avatar
Ian Lynagh committed
442 443 444 445 446
#if defined(DEBUG)
    /* free the thread label table */
    freeThreadLabelTable();
#endif

447 448 449 450 451 452
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	stopFrontPanel();
    }
#endif

453
#if defined(PROFILING) 
454
    reportCCSProfiling();
455 456
#endif

457
    endProfiling();
458
    freeProfiling1();
459

460
#ifdef PROFILING
461 462 463
    // Originally, this was in report_ccs_profiling().  Now, retainer
    // profiling might tack some extra stuff on to the end of this file
    // during endProfiling().
464
    if (prof_file != NULL) fclose(prof_file);
465
#endif
Simon Marlow's avatar
Simon Marlow committed
466

Simon Marlow's avatar
Simon Marlow committed
467 468 469 470 471 472 473
#ifdef EVENTLOG
    if (RtsFlags.EventLogFlags.doEventLogging) {
        endEventLogging();
        freeEventLogging();
    }
#endif

474
#if defined(TICKY_TICKY)
475 476
    if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
#endif
sof's avatar
sof committed
477

478
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
Simon Marlow's avatar
Simon Marlow committed
479
    shutdownAsyncIO(wait_foreign);
sof's avatar
sof committed
480
#endif
Simon Marlow's avatar
Simon Marlow committed
481

482 483 484
    /* free hash table storage */
    exitHashTable();

485
    // Finally, free all our storage
Simon Marlow's avatar
Simon Marlow committed
486
    freeStorage();
487 488 489 490 491 492

#if defined(DEBUG)
    /* and shut down the allocator debugging */
    shutdownAllocator();
#endif

493 494
}

495 496 497 498 499 500 501 502
// The real hs_exit():
void
hs_exit(void)
{
    hs_exit_(rtsTrue);
    // be safe; this might be a DLL
}

503 504 505 506 507 508 509 510 511 512
// Compatibility interfaces
void
shutdownHaskell(void)
{
    hs_exit();
}

void
shutdownHaskellAndExit(int n)
{
Simon Marlow's avatar
Simon Marlow committed
513 514 515 516
    // we're about to exit(), no need to wait for foreign calls to return.
    hs_exit_(rtsFalse);

    if (hs_init_count == 0) {
517 518
	stg_exit(n);
    }
519
}
520

Simon Marlow's avatar
Simon Marlow committed
521 522 523 524 525 526 527 528 529
#ifndef mingw32_HOST_OS
void
shutdownHaskellAndSignal(int sig)
{
    hs_exit_(rtsFalse);
    kill(getpid(),sig);
}
#endif

530
/* 
531
 * called from STG-land to exit the program
532 533
 */

534 535
void (*exitFn)(int) = 0;

536
void  
537
stg_exit(int n)
538
{ 
539 540
  if (exitFn)
    (*exitFn)(n);
541
  exit(n);
542
}