RtsStartup.c 12.8 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 67 68
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
69

mrchebas@gmail.com's avatar
mrchebas@gmail.com committed
70 71 72 73
#if USE_PAPI
#include "Papi.h"
#endif

74 75
// Count of how many outstanding hs_init()s there have been.
static int hs_init_count = 0;
76

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

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

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

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

#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));
}
123 124
#endif

125 126 127
/* -----------------------------------------------------------------------------
   Starting up the RTS
   -------------------------------------------------------------------------- */
128

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

138 139
    setlocale(LC_CTYPE,"");

140 141
    /* Initialise the stats department, phase 0 */
    initStats0();
142 143

    /* Next we do is grab the start time...just in case we're
144 145
     * collecting timing statistics.
     */
146
    stat_startInit();
147

148 149 150 151 152 153
#if defined(DEBUG)
    /* Start off by initialising the allocator debugging so we can
     * use it anywhere */
    initAllocator();
#endif

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

156 157 158 159 160 161
    initRtsFlagsDefaults();

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

    /* Parse the flags, separating the RTS flags from the programs args */
162
    if (argc != NULL && argv != NULL) {
163
	setFullProgArgv(*argc,*argv);
164
	setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
165
	setProgArgv(*argc,*argv);
166
    }
167

168 169 170
    /* Initialise the stats department, phase 1 */
    initStats1();

171 172 173 174
#ifdef USE_PAPI
    papi_init();
#endif

Simon Marlow's avatar
Simon Marlow committed
175
    /* initTracing must be after setupRtsFlags() */
Simon Marlow's avatar
Simon Marlow committed
176
#ifdef DEBUG
Simon Marlow's avatar
Simon Marlow committed
177
    initTracing();
Simon Marlow's avatar
Simon Marlow committed
178
#endif
Simon Marlow's avatar
Simon Marlow committed
179

180 181 182 183 184
    /* initialise scheduler data structures (needs to be done before
     * initStorage()).
     */
    initScheduler();

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

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

191 192 193
    /* 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.
194 195 196
     */
    getStablePtr((StgPtr)base_GHCziTopHandler_runIO_closure);
    getStablePtr((StgPtr)base_GHCziTopHandler_runNonIO_closure);
197 198 199 200 201 202 203
    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);
204

ei@vuokko.info's avatar
ei@vuokko.info committed
205
    /* initialise the shared Typeable store */
206
    initGlobalStore();
ei@vuokko.info's avatar
ei@vuokko.info committed
207

208 209 210 211 212
    /* initialise file locking, if necessary */
#if !defined(mingw32_HOST_OS)    
    initFileLocking();
#endif

sof's avatar
sof committed
213
#if defined(DEBUG)
214 215
    /* initialise thread label table (tso->char*) */
    initThreadLabelTable();
sof's avatar
sof committed
216
#endif
217

218 219
    initProfiling1();

Simon Marlow's avatar
Simon Marlow committed
220 221 222 223 224 225
#ifdef EVENTLOG
    if (RtsFlags.EventLogFlags.doEventLogging) {
        initEventLogging();
    }
#endif

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

sof's avatar
sof committed
230
#if defined(RTS_USER_SIGNALS)
231 232 233 234 235 236
    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
237
#endif
sof's avatar
sof committed
238
 
239
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
sof's avatar
sof committed
240 241 242
    startupAsyncIO();
#endif

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

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

253
    /* Record initialization times */
254
    stat_endInit();
255 256
}

257 258 259 260 261
// Compatibility interface
void
startupHaskell(int argc, char *argv[], void (*init_root)(void))
{
    hs_init(&argc, &argv);
262 263
    if(init_root)
        hs_add_root(init_root);
264 265 266
}


267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
/* -----------------------------------------------------------------------------
   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
283 284
   The code generator inserts a small function "__stginit_<module>" in each
   module and calls the registration functions in each of the modules it
285
   imports.
286 287 288 289 290 291 292 293

   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... 
 */
294
#define INIT_STACK_BLOCKS  4
295
static F_ *init_stack = NULL;
296

297 298
void
hs_add_root(void (*init_root)(void))
299
{
300
    bdescr *bd;
301
    nat init_sp;
302 303 304
    Capability *cap;

    cap = rts_lock();
305

306 307 308 309
    if (hs_init_count <= 0) {
	barf("hs_add_root() must be called after hs_init()");
    }

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

323
    freeGroup_lock(bd);
324

andy@galois.com's avatar
andy@galois.com committed
325 326
    startupHpc();

327 328 329
    // 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
330

331 332
    rts_unlock(cap);

Simon Marlow's avatar
Simon Marlow committed
333 334 335 336
    // ditto.
#if defined(THREADED_RTS)
    ioManagerStart();
#endif
337
}
338

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
/* ----------------------------------------------------------------------------
 * 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
355

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

369 370 371
    /* start timing the shutdown */
    stat_startExit();
    
Simon Marlow's avatar
Simon Marlow committed
372 373
    OnExitHook();

374
#if defined(THREADED_RTS)
375 376 377
    ioManagerDie();
#endif

378
    /* stop all running tasks */
379
    exitScheduler(wait_foreign);
380 381 382

    /* run C finalizers for all active weak pointers */
    runAllCFinalizers(weak_ptr_list);
383
    
384 385 386 387 388 389
#if defined(RTS_USER_SIGNALS)
    if (RtsFlags.MiscFlags.install_signal_handlers) {
        freeSignalHandlers();
    }
#endif

390
    /* stop the ticker */
sof's avatar
sof committed
391
    stopTimer();
392
    exitTimer();
393

394 395 396 397
    /* reset the standard file descriptors to blocking mode */
    resetNonBlockingFd(0);
    resetNonBlockingFd(1);
    resetNonBlockingFd(2);
398

399 400 401 402 403 404 405 406 407 408 409 410
#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++) {
411 412 413
	    struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
	    if (ts != NULL) {
		tcsetattr(fd,TCSANOW,ts);
414 415 416 417 418 419
	    }
	}
	sigprocmask(SIG_SETMASK, &old_sigset, NULL);
    }
#endif

Simon Marlow's avatar
Simon Marlow committed
420 421 422
    // uninstall signal handlers
    resetDefaultHandlers();

423 424 425
    /* stop timing the shutdown, we're about to print stats */
    stat_endExit();
    
andy@galois.com's avatar
andy@galois.com committed
426 427 428
    /* shutdown the hpc support (if needed) */
    exitHpc();

Simon Marlow's avatar
Simon Marlow committed
429 430
    // clean up things from the storage manager's point of view.
    // also outputs the stats (+RTS -s) info.
431 432
    exitStorage();
    
433 434 435
    /* free the tasks */
    freeScheduler();

ei@vuokko.info's avatar
ei@vuokko.info committed
436
    /* free shared Typeable store */
437
    exitGlobalStore();
ei@vuokko.info's avatar
ei@vuokko.info committed
438

439 440 441 442 443
    /* free file locking tables, if necessary */
#if !defined(mingw32_HOST_OS)    
    freeFileLocking();
#endif

Ian Lynagh's avatar
Ian Lynagh committed
444
    /* free the stable pointer table */
445 446
    exitStablePtrTable();

Ian Lynagh's avatar
Ian Lynagh committed
447 448 449 450 451
#if defined(DEBUG)
    /* free the thread label table */
    freeThreadLabelTable();
#endif

452 453 454 455 456 457
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	stopFrontPanel();
    }
#endif

458
#if defined(PROFILING) 
459
    reportCCSProfiling();
460 461
#endif

462
    endProfiling();
463
    freeProfiling1();
464

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

Simon Marlow's avatar
Simon Marlow committed
472 473 474 475 476 477 478
#ifdef EVENTLOG
    if (RtsFlags.EventLogFlags.doEventLogging) {
        endEventLogging();
        freeEventLogging();
    }
#endif

479
#if defined(TICKY_TICKY)
480 481
    if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
#endif
sof's avatar
sof committed
482

483
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
Simon Marlow's avatar
Simon Marlow committed
484
    shutdownAsyncIO(wait_foreign);
sof's avatar
sof committed
485
#endif
Simon Marlow's avatar
Simon Marlow committed
486

487 488 489
    /* free hash table storage */
    exitHashTable();

490
    // Finally, free all our storage
Simon Marlow's avatar
Simon Marlow committed
491
    freeStorage();
492 493 494 495 496 497

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

498 499
}

500 501 502 503 504 505 506 507
// The real hs_exit():
void
hs_exit(void)
{
    hs_exit_(rtsTrue);
    // be safe; this might be a DLL
}

508 509 510 511 512 513 514 515 516 517
// Compatibility interfaces
void
shutdownHaskell(void)
{
    hs_exit();
}

void
shutdownHaskellAndExit(int n)
{
Simon Marlow's avatar
Simon Marlow committed
518 519 520 521
    // we're about to exit(), no need to wait for foreign calls to return.
    hs_exit_(rtsFalse);

    if (hs_init_count == 0) {
522 523
	stg_exit(n);
    }
524
}
525

Simon Marlow's avatar
Simon Marlow committed
526 527 528 529 530 531 532 533 534
#ifndef mingw32_HOST_OS
void
shutdownHaskellAndSignal(int sig)
{
    hs_exit_(rtsFalse);
    kill(getpid(),sig);
}
#endif

535
/* 
536
 * called from STG-land to exit the program
537 538
 */

539 540
void (*exitFn)(int) = 0;

541
void  
542
stg_exit(int n)
543
{ 
544 545
  if (exitFn)
    (*exitFn)(n);
546
  exit(n);
547
}